为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕尼黑5688855 2021-06-30 10:03:49
我有两个数组,一个是 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 回答

?
ITMISS

TA贡献1871条经验 获得超8个赞

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


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

}


查看完整回答
反对 回复 2021-07-09
  • 1 回答
  • 0 关注
  • 144 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信