1

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

2
  • 2
    Might be useful to see the other array and an example of what end result you would like Commented Sep 22, 2020 at 12:53
  • What have you tried so far? Where are you stuck? Commented Sep 23, 2020 at 11:46

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the example it works very well for my data now. Your help has been very much appreciated
@LeslieJarrett Great! I'm glad I was able to help. Can you please mark the answer as accepted? Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.