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

时间:2019-05-26 17:07:00

标签: php codeigniter

我有两个数组,一个是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}]

如何实现上述结果。请帮忙。

1 个答案:

答案 0 :(得分:2)

在您的情况下,我认为加入查询会更有效。

$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) {
    $res = $q->result();
    echo '<pre>';
    print_r($res);
} else {
    echo 'query failed or returned no rows!'; exit;
}