如何将两个数组合并为一个 php

我有两个数组,一个是 codeigniter 查询结果数组,另一个是在 foreach 内部创建的。我的代码是,


$items = array();

$seats_available = 0;

$available_seats = array();


$query = 'SELECT * FROM tbl_buses';

$result = $this->db->query($query);


foreach ($result->result() as $results) {

    $query1 = 'SELECT * FROM tbl_booking WHERE buses_id = '.$results->buses_id.' AND booking_date = "'.$results->buses_date.'" AND booking_status = 1';

    $result1 = $this->db->query($query1);

    $total = $result1->num_rows();

    $seats_available = $results->buses_tot_seat - $total;

    $available_seats[] = array('available_seats' => $seats_available);


    $items[] = $results;

}


return array_merge($items, $available_seats);

现在上面代码的结果是,


[{"buses_id":"1","buses_title":"Sugama Tourist Route No - 31","buses_dept":"20:20","buses_type":"Non A\/C Seater\/Sleeper (2+1)","buses_arr":"05:56","buses_fare":"760","from_place":"Ernakulam","to_place":"Mangalore","buses_date":"2019-04-25","buses_tot_seat":"30"},{"buses_id":"2","buses_title":"test buses","buses_dept":"18:20","buses_type":"test type","buses_arr":"05:56","buses_fare":"1000","from_place":"Ernakulam","to_place":"Mangalore","buses_date":"2019-04-26","buses_tot_seat":"100"},{"available_seats":30},{"available_seats":100}]


但我希望结果为


[{"buses_id":"1","buses_title":"Sugama Tourist Route No - 31","buses_dept":"20:20","buses_type":"Non A\/C Seater\/Sleeper (2+1)","buses_arr":"05:56","buses_fare":"760","from_place":"Ernakulam","to_place":"Mangalore","buses_date":"2019-04-25","buses_tot_seat":"30","available_seats":30},{"buses_id":"2","buses_title":"test buses","buses_dept":"18:20","buses_type":"test type","buses_arr":"05:56","buses_fare":"1000","from_place":"Ernakulam","to_place":"Mangalore","buses_date":"2019-04-26","buses_tot_seat":"100","available_seats":100}]


如何达到上述结果。请帮忙。


慕尼黑5688855
浏览 145回答 1
1回答

ITMISS

我认为在您的情况下,连接查询会更有效。$query = "SELECT buses.*, booking.buses_tot_seat as available_seats FROM tbl_buses as buses LEFT JOIN tbl_booking as booking ON booking.buses_id = buses.buses_id AND booking.booking_status = 1";$q = $this->db->query($query);if ($q && $q->num_rows() > 0) {&nbsp; &nbsp; $res = $q->result();&nbsp; &nbsp; echo '<pre>';&nbsp; &nbsp; print_r($res);} else {&nbsp; &nbsp; echo 'query failed or returned no rows!'; exit;}
打开App,查看更多内容
随时随地看视频慕课网APP