我在PHP中有以下数组(称为$ available_dates):
Array
(
[0] => 2017-11-28
[1] => 2017-11-29
[2] => 2017-11-30
)
此数组传递给查询API的函数,以获取与这些日期相关的游览时间:
for($a=0;$a<count($available_dates);$a++) {
$url = "HTTP API END POINT";
$json = json_decode(get_JSON($url),true);
$total_records = intval($json['total']);
$tour_times = array();
for($b=0;$b<$total_records;$b++) {
//$tour_time is a string e.g. 11:30 AM
$tour_time = $json['item'][$b]['time'];
//Keep track, add to my time array
$tour_times[] = $tour_time;
}
//Issue is here
$available_dates[$a][] = $tour_times;
}
这会在上面指定的行产生以下错误:
[] operator not supported for strings in
我想要创建的是,请原谅我糟糕的格式和表示:
Array
(
[0] => 2017-11-28
array(0 => '12:00 PM', 1 => '2:00 PM')
[1] => 2017-11-29
array(0 => '11:00 PM', 1 => '10:00 PM')
[2] => 2017-11-30
array(0 => '9:00 AM', 1 => '2:00 PM')
)
答案 0 :(得分:1)
您需要将基础$ available_dates结构更改为其中之一:
$available_dates = array(
'2017-11-28'=>array(),
'2017-11-29'=>array(),
'2017-11-30'=>array(),
);
或
$available_dates = Array
(
[0] => array('date'=>'2017-11-28' , 'times'=>array())
[1] => array('date'=>'2017-11-29' , 'times'=>array())
[2] => array('date'=>'2017-11-30' , 'times'=>array())
)
purpuse是在内部数组中保存“times”。
然后当你迭代时,$ available_dates从密钥中获取日期(选项1)或从内部“日期”新密钥中获取日期(选项2), 并且对于API的每个json结果...输入“times”数组
foreach($available_dates AS $k=>$date) {
$url = "HTTP API END POINT";
$json = json_decode(get_JSON($url),true);
$total_records = intval($json['total']);
$tour_times = array();
for($b=0;$b<$total_records;$b++) {
//$tour_time is a string e.g. 11:30 AM
$tour_time = $json['item'][$b]['time'];
//Keep track, add to my time array
$tour_times[] = $tour_time;
}
//option 1
$available_dates[$k] = $tour_times;
// option 2
$available_dates[$k]['times'] = $tour_times;
}
答案 1 :(得分:0)
您可以添加以下内容:
$previous_date = $available_dates[$a];
$available_dates[$a] = array();
$available_dates[$a][] = $previous_date;
$merge = array_merge($available_dates[$a], $tour_times);