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 )
)
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'], " ";
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With