将值添加到foreach循环内的数组 [英] Add values to an array inside a foreach loop

查看:300
本文介绍了将值添加到foreach循环内的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在foreach循环内动态编辑数组.我基本上会分析每个键,如果这个键与我想要的键匹配,我想在该键之后立即在数组中添加另一个条目.

I'm trying to edit an array on the fly, inside a foreach loop. I basically analyse each key, and if this key match the one I want, I want to add another entry in the array immediately after this one.

如果我使用此代码,

$values = array(
    'foo' => 10,
    'bar' => 20,
    'baz' => 30
);

foreach($values as $key => $value){
    print $value . ' ';
    if($key == 'bar'){
        $values['qux'] = 21;
    }
}

我有2个问题,

  • 首先,输出为10 20 30而不是预期的10 20 30 21
  • 第二,即使我解决了第一个问题,我的值仍会在数组的末尾添加
  • first, the output is 10 20 30 instead of the expected 10 20 30 21
  • second, even if I solve the first problem, my value will still be added at the end of my array

如何在barbaz条目之间添加qux条目?

How could I add the qux entry between bar and baz ones?

感谢您的想法.

推荐答案

Foreach不会在循环内遍历添加到数组的新值.

Foreach will not loop through new values added to the array while inside the loop.

如果要在两个现有值之间添加新值,则可以使用第二个数组:

If you want to add the new value between two existing values, you could use a second array:

$values = array(
    'foo' => 10,
    'bar' => 20,
    'baz' => 30
);
$newValues = array();
foreach($values as $key => $value) 
{
    $newValues[$key] = $value;
    if($key == 'bar') 
    {
        $newValues['qux'] = 21;
    }
}
print implode(' ', $newValue);

此外,在StackOverflow上我最喜欢的问题之一是讨论foreach循环: PHP如何"foreach"真的有用吗?

Also, see one of my favorite questions on StackOverflow discussing the foreach loop: How does PHP 'foreach' actually work?

这篇关于将值添加到foreach循环内的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆