Leslie Jarrett
Leslie Jarrett

Reputation: 9

Adding new data to this array

I have an array that has been filled with default data as shown below

$arrivals = array(
    "source" => "arrivals",
    "data" => array(
        0 => array("flight"=>"000","scheduled"=>"0000","city"=>"Geneva","airline"=>"UAL","gate"=>"A00","status"=>"1","remarks"=>"BOARDING"),
        1 => array("flight"=>rand(1,2000),"scheduled"=>randomTime(),"city"=>"Baltimore","airline"=>randomAirline(),"gate"=>"A7","status"=>"0","remarks"=>"") 
    )
);

Now i want to create the same array with data from a table in a loop using the same identifiers such as 'city' but with variable names . The other part is that the first part of 'data' array is a number which of course in a loop I can use a counter.

The problem is that the Array is created with the static value of ""source" => "arrivals" for which there is only one value for the array and then the arrays of 'data'.

I would like an easy way to set up an array dynamically with a number of records but with the one header of ""source" => "arrivals" and multiple entries for "data' i.e. one element per record I fetch from my table

Thank you

Upvotes: 1

Views: 62

Answers (1)

Dave Olson
Dave Olson

Reputation: 148

You can do this with a foreach loop in php after you have retrieved your data.

// Get the data from your table source
$data = get_some_data();

$arrivals = [
  'source' => 'arrivals',
  'data' => []
];

foreach ($data as $city) {
  $arrivals['data'][] = [
    'flight' => $city['flight'],
    'scheduled'=> $city['scheduled'],
    'city' => $city['city'],
    // etc.
  ];
}

Alternatively, if you would like to assign the city name as the array key in arrivals, you can replace the first line inside the foreach loop with $arrivals['data'][$city['city']] (or whatever array item holds the city value).

Upvotes: 1

Related Questions