我正在尝试对一个多维数组进行排序(实际上它是多维的并不重要,因为我总是只排序一个维度。)
function orderSort($a, $b) {
if ($a['order'] == $b['order']) return 0;
return($a['order'] < $b['order']) ? -1 : 1;
}
$nav = array(
"section" => array(
"header" => array(),
"main" => array()
),
"link" => array(
"header" => array(),
"main" => array()
)
);
$DATA = array(
array(
"type" => "section",
"subtype" => "main",
"data" => array("name" => "/Basic", "order" => 1, "parent" => "bbb")
),
array(
"type" => "link",
"subtype" => "main",
"data" => array("name" => "Home", "link" => array("/"), "order" => 1, "parent" => "/Basic")
)
);
foreach($DATA as $ele) {
if(!array_key_exists($ele['data']['parent'], $nav[$ele['type']][$ele['subtype']]))
$nav[$ele['type']][$ele['subtype']][$ele['data']['parent']] = array($ele['data']);
else
array_push($nav[$ele['type']][$ele['subtype']][$ele['data']['parent']], $ele['data']);
}
var_dump($nav['section']['main']);
echo '<br><br>';
foreach($nav['section']['main'] as $ele) {
uasort($ele, 'orderSort');
$nav['section']['main'] = $ele;
}
var_dump($nav['section']['main']);
第一个var_dump
返回:
array(1) {
["bbb"]=> array(1) {
[0]=> array(3) {
["name"]=> string(6) "/Basic"
["order"]=> int(1) ["parent"]=> string(3) "bbb"
}
}
}
正如您所看到的,有一个名为bbb
的密钥(对不起......高度概念化)。现在第二个输出:
array(1) {
[0]=> array(3) {
["name"]=> string(6) "/Basic"
["order"]=> int(1)
["parent"]=> string(3) "bbb"
}
}
突然bbb
消失了。实际上整个数组(只有一个元素)已经消失了。
我的问题是,我可以以某种方式阻止这种情况发生吗?我从来没有要求过这种优化。当然只用一个元素对它进行排序没有任何意义,但仍然存在。
答案 0 :(得分:1)
foreach($nav['section']['main'] as $ele) {
uasort($ele, 'orderSort');
$nav['section']['main'] = $ele;
}
好。哪个是关键?你忘记了键(你用新数组而不是原始数组本身覆盖原始数组的父级):
foreach($nav['section']['main'] as $key => $ele) {
uasort($ele, 'orderSort');
$nav['section']['main'][$key] = $ele;
}
是正确的,但参考更好:
foreach($nav['section']['main'] as &$ele) {
uasort($ele, 'orderSort');
}
答案 1 :(得分:0)
你的问题在这里:
foreach($nav['section']['main'] as $ele) {
uasort($ele, 'orderSort');
$nav['section']['main'] = $ele;
}
这需要
foreach($nav['section']['main'] as $index => $ele) {
uasort($ele, 'orderSort');
$nav['section']['main'][$index] = $ele;
}
你用第一个元素替换了整个$ nav ['section'] ['main']。