我有以下數組。我需要排序的嵌套數組鍵[ID]此數組:PHP排序多維數組
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)
)
我有以下數組。我需要排序的嵌套數組鍵[ID]此數組:PHP排序多維數組
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)
)
,你可以做這樣的
foreach($arr as $val) {
$ret[$val['id']] = $val['category_id'];
}
ksort($ret);
如果你想獲得相同的數組進行排序,那麼你可以添加以下代碼:
foreach($ret as $key=>$val) {
$newArr[] = array('id'=>$key,'category_id'=>$val);
}
嘗試array_multisort
它將通過內陣列的第一密鑰/屬性
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);
}
使用usort與外數組進行排序自定義比較功能。
<?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'], " ";
您可能要使用array_multisort 請查看文檔中的示例#3。
重複的http://stackoverflow.com/questions/3376607/help-sorting-this-array/3376735#3376735 – stillstanding 2010-08-06 14:19:43