在此处的//print_r($reunits);
下面的PHP代码中输出:http://pastebin.com/RbqZ5kHV
但在此处echo json_encode($reunits);
输出为:http://pastebin.com/GFdHkg5Y
如果使用$reunits = array('reunits'=>$units_data);
:$reunits .=...
,我会在echo json_encode($reunits);
中获得此输出:“ArrayArrayArray”
如何将//print_r($reunits);
的输出输出放在输出echo json_encode($reunits);
上?怎么解决它?
$reunits = "";
//$tourf_id = $this->input->post('tour_name');
$tourf_id = '102';
//$query_r = $this->db->order_by('id','desc')->get_where('tour_foreign_residence', array('relation' => $tourf_id));
$query_r = array('77192276', '15190364', '15183965')
foreach($query_r->result() as $idx=>$val){
$hotel_id = $val->hotel_id;
$query = $this->db->get_where('tour_foreign_units', array('hotel_id' => $hotel_id));
$units_data = array();
foreach ($query->result() as $index=>$row) {
$units_data[] = array(
'name' => $row->name,
'price' => $row->price,
'extra' => $row->extra,
'hotel_id' => $row->hotel_id
);
}
$reunits = array('reunits'=>$units_data);
//print_r($reunits);
}
echo json_encode($reunits);
此输出由json_encode发送到jquery中的ajax调用。
答案 0 :(得分:0)
如果使用string concatenation operator (.
)连接数组,则数组将转换为字符串(在PHP中为"Array"
),然后连接。
改为使用array operator:
$reunits+=...
将两个数组联合起来。如果联盟不是您想要的,您可以使用array_merge
。
不要忘记将顶部的变量初始化为空数组:
$reunits = array();
答案 1 :(得分:0)
如果我理解你的要求,而不是尝试使用.=
附加到数组上,那么你应该使用[]
表示法附加到数组:
//Initialize reunits as an array
$reunits = array();
foreach($query_r->result() as $idx=>$val){
$hotel_id = $val->hotel_id;
$query = $this->db->get_where('tour_foreign_units', array('hotel_id' => $hotel_id));
$units_data = array();
foreach ($query->result() as $index=>$row) {
$units_data[] = array(
'name' => $row->name,
'price' => $row->price,
'extra' => $row->extra,
'hotel_id' => $row->hotel_id
);
}
// Append the array $units_data onto $reunits
// since $units_data is already an array
$reunits[] = $units_data;
}
// Now the JSON output should look like you expect
echo json_encode($reunits);