Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sorting multidimensional arrays

I have the following array. I need to sort this array by the nested array key [id]:

Array ( 
[0] => Array ( [id] => 5 [category_id] => 12 )
[1] => Array ( [id] => 3 [category_id] => 12 )
[2] => Array ( [id] => 9 [category_id] => 12 )
[3] => Array ( [id] => 4 [category_id] => 12 )
)
like image 436
kalpaitch Avatar asked Aug 06 '10 13:08

kalpaitch


2 Answers

Use usort with a custom comparison function.

<?php

function cmp($a, $b) {
  if ($a['id'] == $b['id'])
    return 0;
  return $a['id'] < $b['id'] ? -1 : 1;
}

$array = Array ( 
  0 => Array ( 'id' => 5, 'category_id' => 12 ),
  1 => Array ( 'id' => 4, 'category_id' => 12 ),
  2 => Array ( 'id' => 7, 'category_id' => 12 ),
  3 => Array ( 'id' => 3, 'category_id' => 12 ),
);

usort($array, 'cmp');

// Output: 3 4 5 7 
foreach ($array as $element)
   echo $element['id'], " ";
like image 164
meagar Avatar answered Oct 16 '22 23:10

meagar


you can do it like this

foreach($arr as $val) {
    $ret[$val['id']] = $val['category_id'];
}
ksort($ret);

in case you want to get the same array sorted then you can add the following code:

foreach($ret as $key=>$val) {
    $newArr[] = array('id'=>$key,'category_id'=>$val);
}
like image 33
Tornike Avatar answered Oct 16 '22 22:10

Tornike