简体   繁体   中英

Put output in json_encode?

In following php code in here //print_r($reunits); is output this: http://pastebin.com/RbqZ5kHV

but in here echo json_encode($reunits); is output as: http://pastebin.com/GFdHkg5Y

If use $reunits = array('reunits'=>$units_data); as: $reunits .=... i get this output in echo json_encode($reunits); : "ArrayArrayArray"

How can put output like output in //print_r($reunits); on output echo json_encode($reunits); ? How can fix it?

$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);

This output send by json_encode to ajax call in jquery.

If you concat arrays with the string concatenation operator ( . ) , the arrays will be converted into a string (that is "Array" in PHP) and then concatenated.

Use an array operator instead:

$reunits+=...

which will union two arrays. If union is not what you're looking for, you can use array_merge .

Don't forget to initialize the variable at the top as an empty array as well:

$reunits = array();

If I understand what you are asking, rather than attempting to append onto the array with .= , you should be using the [] notation to append to the 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM