PHP将数组追加到子数组 [英] PHP Append an array to a sub array
问题描述
我需要创建一个位置数组,它必须看起来像这样
I need to make an array of locations arrays, it must look like this
$relevanceKeys = array(
'locations' => array(
array(
'longitude' => '123456',
'latitude' => '123456'
),
array(
'longitude' => '123456',
'latitude' => '123456'
)
... more arrays
)
);
但是我需要即时生成它们,所以它的开始就像
However I need to generate those on the fly, so it starts out like
$relevanceKeys = array(
'locations' => array(
)
);
然后我要从数据库中找到的行中添加每个数组:
And then I want to add each array from a row I found in the database:
while ($row = $result->fetch_object()) {
$array = array(
array (
'longitude' => $row->longitude,
'latitude' => $row->latitude
)
);
$relevanceKeys['locations'] = $relevanceKeys['locations'] + $array;
}
但这不起作用,之后该文件不可读.它已导出为另一种格式,所以我看不到它是否正确地变成了阵列树.
This does not work though, afterwards the file is not readable. It's exported to a different format so I can't see if it turns into the array tree correctly.
我从此处阅读了如何添加PHP数组 http://php.net/manual/zh-CN/function.array-merge.php
I read how to append PHP arrays from here http://php.net/manual/en/function.array-merge.php
我尝试了未嵌套的 $ array
并嵌套在现在的另一个数组中,没有运气
I tried unnested $array
and nested in another array as it is now, no luck
推荐答案
只需追加如下数组:
$relevanceKeys['locations'][] = $array;
//^^ See here
您不必一直合并它们!
另外,我认为您想更改此内容:
Also I think you want to change this:
$array = array(
array (
'longitude' => $row->longitude,
'latitude' => $row->latitude
)
);
为此,您将获得预期的结构:
to this to get your expected structure:
$array = array(
'longitude' => $row->longitude,
'latitude' => $row->latitude
);
有关数组的更多信息,请参见手册: http://php.net/manual/zh-CN/language.types.array.php
For more information about array see the manual: http://php.net/manual/en/language.types.array.php
这篇关于PHP将数组追加到子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!