0

I have an array and i need all items with the same id [id_promo] or [name] to be grouped and if possible all names to be ordered by alfabetic order

my array is :

   Array ( 
[0] => Array ( [nome] => 0012 – Inês Marinho Lopes [id_promo] => 1897 [foto] => 1898 [entrega] => 12/03/2016 [devoluçao] => 18/03/2016 [devolvido] => Não ) 
[1] => Array ( [nome] => 0015 – Daniela Palhares [id_promo] => 1912 [foto] => 1913 [entrega] => 30/03/2016 [devoluçao] => 29/03/2016 [devolvido] => Não ) 
[2] => Array ( [nome] => 0031 – Cláudia Fonseca [id_promo] => 2026 [foto] => 2027 [entrega] => [devoluçao] => [devolvido] => Não ) 
[3] => Array ( [nome] => 0015 – Daniela Palhares [id_promo] => 1912 [foto] => 1913 [entrega] => 30/03/2016 [devoluçao] => 29/03/2016 [devolvido] => Não ) 
) 

and i need them to be grouped like this :

Array ( 
[0] => Array ( [nome] => 0031 – Cláudia Fonseca [id_promo] => 2026 [foto] => 2027 [entrega] => [devoluçao] => [devolvido] => Não  ) 
[1] => Array ( [nome] => 0015 – Daniela Palhares [id_promo] => 1912 [foto] => 1913 [entrega] => 30/03/2016 [devoluçao] => 29/03/2016 [devolvido] => Não ) 
[2] => Array ( [nome] => 0015 – Daniela Palhares [id_promo] => 1912 [foto] => 1913 [entrega] => 30/03/2016 [devoluçao] => 29/03/2016 [devolvido] => Não ) 
[3] => Array ( [nome] => 0012 – Inês Marinho Lopes [id_promo] => 1897 [foto] => 1898 [entrega] => 12/03/2016 [devoluçao] => 18/03/2016 [devolvido] => Não ) 
) 

i tried a few foreach combinations but i cant make it work...

tks

Bruno Alex
  • 63
  • 1
  • 12
  • If I understand your example correctly, you don't need to change the structure of the array, just sort it into the right order. If so, see [this reference answer](http://stackoverflow.com/a/17364128/157957). – IMSoP Mar 03 '16 at 14:34
  • Possible duplicate of [How can I sort arrays and data in PHP?](http://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – IMSoP Mar 03 '16 at 14:34

2 Answers2

0

You can try something like this:

$newArray = Array();
foreach($oldArray as $key => $item)
{
   $newArray[$item['id_promo']][$key] = $item;
}

ksort($newArray, SORT_NUMERIC);

Reference for ksort()

Lorenzo Belfanti
  • 974
  • 3
  • 15
  • 42
  • tks for the help..but not im getting :Array ( [2026] => Array ( [6] => Array ( [nome] => 0031 – Cláudia Fonseca =>.. and not [0] => Array ( [nome] => 0031 – Cláudia Fonseca – Bruno Alex Mar 03 '16 at 15:19
0

you can use the method uasort combined with a callback function

$arr = Array(); //This is your base array
function compare($a, $b) {
    if ($a['nome'] == $b['nome']) {
        return 0;
    }
    return ($a['nome'] < $b['nome']) ? 1 : -1;
}

usort($arr, 'compare');

This will sort your array only on the [nome] Key. I think you should try to enhanced this to work with [id_promo] and/or [name].

You can find a detailed documentation on usort

Unex
  • 1,710
  • 11
  • 16