0

I want to code some associative arrays from the database in this way. But it creates some errors. I want to know what are the faults.

$rid = $request->input('result_id');
$passenger = Passenger::select('*')->where('result_id', $rid)->get();

$booking_data = array(
  "SearchID"  => $request->input('search_id'),
  "ResultID"  => $request->input('result_id'),
  "Passengers"  => array(
            foreach ($passenger as $key => $passengers) {
             [
               "Title"        => $passengers->title,
               "FirstName"    => $passengers->first_name,
               "LastName"     => $passengers->last_name,
               "PaxType"      => $passengers->pax_type
             ]
            }
          )
      );
  • The assigned variable is missing. And since `$key` is not used, you can simply remove it as well. In other words, you need a variable to assign your array construct to. – Guido Faecke Jun 16 '22 at 05:05
  • You can't place a foreach inside of an array like that. – Kevin Y Jun 16 '22 at 05:06
  • Ah... you can't put a `foreach` into an `array` definition. That's not working as is. – Guido Faecke Jun 16 '22 at 05:08
  • Is there any other way? put a foreach into an array. @GuidoFaecke – Noor Mohammad Babu Jun 16 '22 at 05:11
  • Set up a variable before trying to populate your booking data. `$ar = [];foreach ($passenger as $p) {$ar[] = ['Title' => $p->title,'FirstName' => $p->first_name,'LastName' => $p->last_name,'PaxType' => $p->pax_type];}` Then use `"Passengers" => $ar` inside of your booking data. – Kevin Y Jun 16 '22 at 05:16
  • $rid = $request->input('result_id'); $passengers = Passenger::select('*')->where('result_id', $rid)->get(); $booking_data = [ "SearchID" => $request->input('search_id'), "ResultID" => $request->input('result_id'), ]; foreach ($passengers as $passenger) { $booking_data['Passengers'] = [ "Title" => $passengers->title, "FirstName" => $passengers->first_name, "LastName" => $passengers->last_name, "PaxType" => $passengers->pax_type ]; } – Guido Faecke Jun 16 '22 at 05:19
  • thanks, @KevinY & GuidoFaecke .. its works :) – Noor Mohammad Babu Jun 16 '22 at 05:36

0 Answers0