php 如何使用php将元素添加到循环中的数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9581966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to add elements to an array in a loop using php
提问by user658182
I am dynamically trying to populate a multidimensional array and having some trouble.
我正在动态地尝试填充多维数组并遇到一些麻烦。
I have a list of US states. Associative array like this $states[nc], $states[sc], etc. in my loop I want to append cities onto each state so $states[nc][cities] contains an array of cities. Im stuck with the logic.
我有一份美国各州的名单。像这样的关联数组 $states[nc]、$states[sc] 等。在我的循环中,我想将城市附加到每个州,以便 $states[nc][cities] 包含一个城市数组。我坚持逻辑。
foreach($states as $state) {
$data[$state] = $state;
foreach($cities as $city) {
$data[$state]['cities'] .= $city;
}
}
I know that concatenation is not correct, but I am not sure how to add elements to this array. I keep getting errors with array_push.
我知道串联不正确,但我不确定如何向该数组添加元素。我不断收到 array_push 错误。
What's the correct way to add these elements?
添加这些元素的正确方法是什么?
回答by Jon
The same way you add to an array when the key is not a concern:
与键无关时添加到数组的方式相同:
$data[$state]['cities'][] = $city;
回答by ckonig
In PHP, you can fill an array without referring to the actual index.
在 PHP 中,您可以在不引用实际索引的情况下填充数组。
$newArray = array();
foreach($var in $oldArray){
$newArray[] = $var;
}
回答by PiTheNumber
To add an element, use empty brackets.
要添加元素,请使用空括号。
foreach($states as $state) {
foreach($cities as $city) {
$data[$state][] = $city;
}
}
This will create an array like this
这将创建一个这样的数组
array(
'nc' => array('city1', 'city2', ...),
'sc' => array('city1', 'city2', ...)
)
See manualunder "Creating/modifying with square bracket syntax"
请参阅“使用方括号语法创建/修改”下的手册
回答by Harti
foreach($states as $state) {
$data[$state] = $state;
foreach($state->cities as $city) {
$data[$state][] = $city;
}
}
Using empty brackets adds an element to the array.
使用空括号向数组添加一个元素。