开发者

PHP sorting multidimensional arrays

开发者 https://www.devze.com 2023-01-10 18:04 出处:网络
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 )

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


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


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消