views:

62

answers:

6

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 )
)
A: 

try array_multisort it will sort the outer array by the first key/property of the inner arrays

zolex
A: 
function sort_by_field($field, & $data) {
    $sort_func = create_function('$a,$b', 'if ($a["' . $field . '"] == $b["' . $field . '"]) {return 0;} 
            return ($a["' . $field . '"] < $b["' . $field . '"]) ? -1 : 1;');

    uasort($data, $sort_func);
}
Codler
+6  A: 

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'], " ";
meagar
+1 a good , universal solution.
Centurion
You could just return `$a['id'] - $b['id']` in the `cmp` function.
Artefacto
+1  A: 

Why not just store your data like this?

Array ( 
    [5] => int(12)
    [3] => int(12)
    [9] => int(12)
    [4] => int(12)
)

Then you can just use ksort() as usual.

Dolph
This is how I do arrays where I just need to map two numbers together. It may not be as explicit, but it does make working with it a hell of a lot easier.
tj111
+2  A: 

You're probably going to want to use array_multisort Look at example #3 in the documentation.

speshak
+1  A: 

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);
}
KoKo