[英]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.现在我想使用相同的标识符(例如“city”但具有变量名)在循环中使用表中的数据创建相同的数组。 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'.问题是数组是用“source”=>“arrivals”的 static 值创建的,数组只有一个值,然后是“数据”的 arrays。
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' ie one element per record I fetch from my table我想要一种简单的方法来动态地设置一个包含许多记录的数组,但是使用“源”=>“到达”的一个 header 和“数据”的多个条目,即我从我的表中获取的每个记录一个元素
Thank you谢谢
You can do this with a foreach
loop in php after you have retrieved your data.检索数据后,您可以在 php 中使用foreach
循环执行此操作。
// 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).或者,如果您想将城市名称指定为 arrivals 中的数组键,您可以将 foreach 循环内的第一行替换为$arrivals['data'][$city['city']]
(或任何数组项持有城市价值)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.