我有一个像这样的数组
"entry a" => [
"type": 3,
"id": 1,
"content" => [
[
"name" => "somename a",
"date": => "2011-08-2"
],
[
"name" => "somename b",
"date": => "2012-04-20"
],
[
"name" => "somename c",
"date": => "2015-01-14"
],
]
],
"entry b" => [
"type": 3,
"id": 2,
"content" => [
[
"name" => "someothername a",
"date": => "2011-01-6"
],
[
"name" => "someothername b",
"date": => "2015-12-24"
],
[
"name" => "someothername c",
"date": => "2016-01-01"
],
]
],
...
我想按日期排序每个条目的“内容”数组。我尝试了以下内容;
foreach ($cfArray as $cfEntry) {
if($cfEntry['type'] == '3' && !is_null($cfEntry['content'])) {
$content = $cfEntry['content'];
uasort($content, function($a, $b) {
$a_end = strtotime($a['date']);
$b_end = strtotime($b['date']);
return ($a_end > $b_end) ? -1 : 1;
});
$cfEntry['content'] = $content;
}
}
如果我在排序之前和之后比较$ content,它已经改变但是我的$ cfArray没有改变。这是为什么?还有另一种方法可以对此进行排序吗?
答案 0 :(得分:1)
您的代码几乎正常工作,您可以使用此示例将更改的项目保存到$newCfArray
数组,从而完全创建它:
$newCfArray = array();
foreach ($cfArray as $key => $cfEntry) {
if($cfEntry['type'] == '3' && !is_null($cfEntry['content'])) {
$content = $cfEntry['content'];
uasort($content, function($a, $b) {
$a_end = strtotime($a['date']);
$b_end = strtotime($b['date']);
return ($a_end > $b_end) ? -1 : 1;
});
$cfEntry['content'] = $content;
}
$newCfArray[$key] = $cfEntry;
}
$cfArray = $newCfArray;