我有一个需要按第三级排序的数组。
我需要按fullname
值对数组进行排序。这可能吗?
$array = array(
'family1' => array(
'family_data' => array(
'fullname' => 'Samuel Smith',
'...' => '...'
)
),
'family2' => array(
'family_data' => array(
'fullname' => 'John Doe',
'...' => '...'
)
),
'family3' => array(
'family_data' => array(
'fullname' => 'Adrian Chan',
'...' => '...'
)
)
);
更容易阅读:
Array
(
[family1] => Array
(
[family_data] => Array
(
[fullname] => Samuel Smith
[...] => ...
)
)
[family2] => Array
(
[family_data] => Array
(
[fullname] => John Doe
[...] => ...
)
)
[family3] => Array
(
[family_data] => Array
(
[fullname] => Adrian Chan
[...] => ...
)
)
)
期望的结果是:
Array
(
[family3] => Array
(
[family_data] => Array
(
[fullname] => Adrian Chan
[...] => ...
)
)
[family2] => Array
(
[family_data] => Array
(
[fullname] => John Doe
[...] => ...
)
)
[family1] => Array
(
[family_data] => Array
(
[fullname] => Samuel Smith
[...] => ...
)
)
)
答案 0 :(得分:4)
使用uasort
uasort - 使用用户定义的比较函数对数组进行排序并维护索引关联
uasort($array, function($a, $b) {
return strcmp($a['family_data']['fullname'], $b['family_data']['fullname']);
});
测试:
$array = array(
'family1' => array(
'family_data' => array(
'fullname' => 'Ben Smith',
'...' => '...',
'...' => '...'
),
'...' => '...',
'...' => '...'
),
'family2' => array(
'family_data' => array(
'fullname' => 'John Doe',
'...' => '...',
'...' => '...'
),
'...' => '...',
'...' => '...'
),
'family3' => array(
'family_data' => array(
'fullname' => 'Aen Smith',
'...' => '...',
'...' => '...'
),
'...' => '...',
'...' => '...'
),
);
uasort($array, function($a, $b) {
return strcmp($a['family_data']['fullname'], $b['family_data']['fullname']);
});
print_r($array);
输出:
Array
(
[family3] => Array
(
[family_data] => Array
(
[fullname] => Aen Smith
[...] => ...
)
[...] => ...
)
[family1] => Array
(
[family_data] => Array
(
[fullname] => Ben Smith
[...] => ...
)
[...] => ...
)
[family2] => Array
(
[family_data] => Array
(
[fullname] => John Doe
[...] => ...
)
[...] => ...
)
)
答案 1 :(得分:1)
试试这个:
$sort = array();
foreach($your_array as $k=>$v) {
$sort['fullname'][$k] = $v['family_data']['fullname'];
}
array_multisort($sort['fullname'], SORT_ASC, $your_array);
echo "<pre>";
print_r($your_array);
答案 2 :(得分:0)
http://www.php.net/manual/en/function.array-multisort.php 看看示例3,我认为这会帮助你。
答案 3 :(得分:0)
Sort array of objects by object fields
您可以使用PHP usort
函数执行此操作
http://php.net/manual/en/function.usort.php