我看到了很多关于多维数组的问题,以及如何构建它们,同时尝试一些答案,我仍然得到一个错误。所以我想我要做的是不可能的,也许我应该使用JSON代替?
我有一个数据源作为JSON对象返回的数据。它里面有很多数据,我只需要一小部分。现在我需要把它按日期排序:
$temp_array = array();
foreach ($data as $booking_id => $booking) {
$setdate = '';
$b = $this->getBooking($booking_id);
foreach ($b as $k => $v) {
$setdate = date('d-m-Y', $booking['start_date']);
if(!in_array($setdate, $temp_array)) {
$temp_array = array('date' => $setdate);
}
$temp_array['date'][] = array($k => $v);
}
}
我需要日期是数组的第一个节点,数据是在第二个节点。当在迭代中发现新的日期时,它会创建另一个新节点:
[0] => 1/10/16
[0] => array( ['key'] =>['value'])
[1] => array( ['key'] =>['value'])
[2] => array( ['key'] =>['value'])
[1] => 7/10/16
[0] => array( ['key'] =>['value'])
[1] => array( ['key'] =>['value'])
[2] => array( ['key'] =>['value'])
[2] => 14/10/16
[0] => array( ['key'] =>['value'])
[1] => array( ['key'] =>['value'])
[2] => array( ['key'] =>['value'])
[3] => 21/10/16
[0] => array( ['key'] =>['value'])
[1] => array( ['key'] =>['value'])
[2] => array( ['key'] =>['value'])
我似乎无法得到任何地方,因为我得到的错误是指[] operator not supported for strings
或Warning: Attempt to modify property of non-object in
,这取决于我在这里发现的其他例子。
我认为这里的问题是,数据没有任何顺序,所以它可能填充节点[0],然后[3],然后回到[0],等等。
你知道我到底做错了什么吗?
感谢阿迪
使用下面的代码,这是中间的foreach:
$b = $this->getBooking($booking_id);
foreach ($b as $k => $v) {
$setdate = date('d-m-Y', strtotime($booking['date_desc']));
if(!in_array($setdate, $temp_dates)) {
array_push($temp_dates, $setdate);
$temp_array[]['date'] = $setdate;
}
}
给出如下结果:
Array ( [0] => Array ( [date] => 22-10-2016 )
[1] => Array ( [date] => 01-10-2016 )
[2] => Array ( [date] => 08-10-2016 )
[3] => Array ( [date] => 15-10-2016 )
)
正确。现在,我需要添加,每次到达$tem_array有标题的日期时,添加另一个数组:
Array ( [0] => Array ( [date] => 22-10-2016 ) => [0] => $data
[1] => $data
[2] => $data
[1] => Array ( [date] => 01-10-2016 ) => [0] => $data
[1] => $data
[2] => $data
[2] => Array ( [date] => 08-10-2016 ) => [0] => $data
[3] => Array ( [date] => 15-10-2016 ) => [0] => $data
[1] => $data
)
希望这能解释得更好一点。我的第一个位是正确的,但是当日期已经在那里时,我需要向上移动一个节点。
我想我把它复杂化了。这是我想要的最终代码。
function sortcf($data) {
$temp_array = array();
$temp_dates = array();
foreach ($data as $booking_id => $booking) {
$b = $this->getBooking($booking_id);
$setdate = date('d-m-Y', strtotime($booking['date_desc']));
$temp_array[$setdate][] = ($b);
}
$this->wcg_am_data = $temp_array;
}