我目前正在尝试根据日期和名称对数据进行分组。这是我的代码
$data = [];
foreach($allmatches as $d){
$name = $d['div']['divisionName'];
$data[$d['playingDate']][$name][]=$d;
$data[$d['playingDate']]['day']=$d['day'];
$data[$d['playingDate']]['month']=$d['month'];
$data[$d['playingDate']]['isToday']=$d['isToday'];
}
return $data;
OUTPUT
======
2018-09-18: {
Elitserien: [+],
day: "18",
month: "Sep",
isToday: true,
Division 2: [+],
Division 5: [+]
},
当前输出以Elitserien
开头,但我想在一开始就达到Division 5
。
我想总是在数组的开头插入新元素。我该怎么做?非常感谢。
答案 0 :(得分:1)
您可以简单地使用+
运算符:
$data = [];
foreach($allmatches as $d){
$name = $d['div']['divisionName'];
// Prepare a temp array
$temp = array();
$temp[$name][] = $d;
$temp['day'] = $d['day'];
$temp['month'] = $d['month'];
$temp['isToday'] = $d['isToday'];
// Add to the beginning of $data array (first-level)
$data = array($d['playingDate'] => $temp) + $data;
}
return $data;
答案 1 :(得分:1)
由于您使用的是关联数组,因此需要使用array_merge
来添加序列数据(即,由$name
索引的数据到$data[$d['playingDate']]
数组的开头。此代码将做您想要的事情。请注意,我将系列代码放在最后,以避免必须检查$data[$d['playingDate']]
和$data[$d['playingDate']][$name]
的设置。
$data = [];
foreach($allmatches as $d){
$name = $d['div']['divisionName'];
$data[$d['playingDate']]['day']=$d['day'];
$data[$d['playingDate']]['month']=$d['month'];
$data[$d['playingDate']]['isToday']=$d['isToday'];
if (!isset($data[$d['playingDate']][$name])) $data[$d['playingDate']] = array_merge(array($name => array()), $data[$d['playingDate']]);
$data[$d['playingDate']][$name][]=$d;
}
我创建了一个小的demo on 3v4l.org
答案 2 :(得分:-2)
array_unshift()
功能将解决您的问题。