使用我当前的代码,我从我的d json_encode base中获得了正确的详细信息。
[{
"tour_id": "1",
"tour_name": "Test this",
"start": "2016-01-12 13:21:32",
"end": "2016-01-15 13:21:35",
"itinerary_photo": "Desert.jpg"
}][{
"tour_id": "3",
"tour_name": "Everest",
"start": "2016-02-10 13:23:00",
"end": "2016-02-18 13:23:07",
"itinerary_photo": "Chrysanthemum.jpg"
}]
预期的 JSON 源
我正在使用 json 提要将事件添加到全日历。我的json_encode结果的格式应该是这样的:
[{
"tour_id": "1",
"tour_name": "Test this",
"start": "2016-01-12 13:21:32",
"end": "2016-01-15 13:21:35",
"itinerary_photo": "Desert.jpg"
}, {
"tour_id": "3",
"tour_name": "Everest",
"start": "2016-02-10 13:23:00",
"end": "2016-02-18 13:23:07",
"itinerary_photo": "Chrysanthemum.jpg"
}]
不同之处在于对象仅存储到一个数组中。随着输出 im 的获取,它显示多个数组。
这是我的控制器代码:
public function getBookedCal(){
if ($this->session->userdata('login')==true){
$data['twimembers'] = $this->session->userdata('twimembers');
$data['tour'] = $this->Model_MyBookedTours->getPaidTours($data['twimembers']['user_id']);
foreach ($data['tour'] as $tourConfirm){
$tourConfirm = $this->Model_MyBookedTours->getTourInfo($tourConfirm['Tour_packages_tourpkg_id']);
echo json_encode($tourConfirm);
}
//echo json_encode($tourConfirm); //this outputs only a single array
}//end if
}//end function
型:
function getPaidTours($user_id){
$this->db->where('User_accounts_user_id',$user_id);
$this->db->where('payment_status','1'); //confirmed
$query = $this->db->get('user_tourpkg');
return $query->result_array();
} //calendar
function getTourInfo($tour_id){
$this->db->select('tour_id,tour_name, start, end, itinerary_photo');
$this->db->where('tour_id',$tour_id);
$query = $this->db->get('tour_packages');
return $query->result();
}
有什么方法可以通过对代码进行一些调整来获得预期的 JSON 源?
不要使用变量使用数组,不要使用 foreach 值作为赋值
$tmptourConfirm = array();
foreach ($data['tour'] as $tourConfirm){
$tmptourConfirm[] = $this->Model_MyBookedTours->getTourInfo($tourConfirm['Tour_packages_tourpkg_id']);
}
echo json_encode($tmptourConfirm);
您必须在每个
循环之前将$tourConfirm
声明为数组,并在循环后将该数组编码为json。
例如
public function getBookedCal(){
if ($this->session->userdata('login')==true){ $tmptourConfirm = array(); $data['twimembers'] = $this->session->userdata('twimembers');
$data['tour'] = $this->Model_MyBookedTours->getPaidTours($data['twimembers']['user_id']);
foreach ($data['tour'] as $tourConfirm){
$tourConfirm[] = $this->Model_MyBookedTours->getTourInfo($tourConfirm['Tour_packages_tourpkg_id']);
}
echo json_encode($tourConfirm);
}//end if
}/
按如下方式更改getBookedCal()
,
public function getBookedCal(){
$tourConfirm = array();
if ($this->session->userdata('login')==true){
$data['twimembers'] = $this->session->userdata('twimembers');
$data['tour'] = $this->Model_MyBookedTours->getPaidTours($data['twimembers']['user_id']);
foreach ($data['tour'] as $tourConfirm){
$tourConfirm[] = $this->Model_MyBookedTours->getTourInfo($tourConfirm['Tour_packages_tourpkg_id']);
}
//echo json_encode($tourConfirm); //this outputs only a single array
}//end if
echo json_encode($tourConfirm);
}//end function