[英]Trouble Adding New Item to Array
I have an array that I need to add some key/value pairs too but I'm having trouble with it. 我有一个数组,我也需要添加一些键/值对,但是我遇到了麻烦。 Here's an example of my array: 这是我的数组的一个示例:
Array
(
[0] => Array
(
[id] => 108
[pagetitle] => Title
[description] =>
[parent] => 35
[alias] => url-alias
[menutitle] =>
)
)
I'm trying to insert a new key called "country" along with it's value but I can't figure out what I'm doing wrong. 我正在尝试插入一个名为“国家/地区”的新键及其值,但是我无法弄清楚自己在做什么错。
foreach($all_items as $item) {
$country = $modx->getTemplateVarOutput(array("country"), $item['id'], $published=1);
$item['country'] = $country['country'];
}
I've verified that $country['country']
does contain what I need it to...I just can't seem to add it to the array. 我已经验证了$country['country']
确实包含了我所需要的东西...我似乎无法将其添加到数组中。
You need to pass array element by reference if you want to modify it. 如果要修改数组元素,则需要按引用传递它。
foreach($all_items as &$item) {
...
That is because the $item
array is actually only a copy of the the element within $all_items
. 那是因为$item
数组实际上只是$all_items
元素的一个副本。
To achieve what you want you could do it like this: 要实现您想要的目标,您可以这样做:
foreach($all_items as &$item) {
$country = $modx->getTemplateVarOutput(array("country"), $item['id'], $published=1);
$item['country'] = $country['country'];
}
Also see docs for foreach there you'll find exactly that. 另请参阅foreach文档,在那里您会找到确切的信息。
This should do what you are asking: 这应该按照您的要求进行:
foreach($all_items as $k=>$v) {
$country = $modx->getTemplateVarOutput(array("country"), $all_items[$k]['id'], $published=1);
$all_items[$k]['country'] = $country['country'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.