[英]Put output in json_encode?
在下面的PHP代碼中//print_r($reunits);
輸出如下: http : //pastebin.com/RbqZ5kHV
但在這里echo json_encode($reunits);
輸出為: http : //pastebin.com/GFdHkg5Y
如果使用$reunits = array('reunits'=>$units_data);
如: $reunits .=...
我在echo json_encode($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調用。
如果使用字符串連接運算符( .
)連接數組,則數組將轉換為字符串(PHP中為"Array"
),然后進行連接。
改用數組運算符 :
$reunits+=...
這將合並兩個數組。 如果union不是您要查找的內容,則可以使用array_merge
。
不要忘記將頂部的變量也初始化為空數組:
$reunits = array();
如果我理解您的要求,而不是嘗試使用.=
追加到數組,則應使用[]
表示法追加到數組:
//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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.