将数据插入到foreach中的关联数组中

时间:2014-05-28 13:08:51

标签: php

所以我有这个数组$companies,如下所示:

array(
    (int) 0 => array(
        'Company' => array(
            'id' => '54',
            'name' => 'Company 1',
            'phone' => '867038198',
            'start_date' => '2014-04-11'
        )
    ),
    (int) 1 => array(
        'Company' => array(
            'id' => '55',
            'name' => 'Company 2',
            'phone' => '867038199',
            'start_date' => '2014-04-23'
        )
    ))

然后我有以下foreach循环:

foreach($companies as $company){

    $count = 3;
    $company['Company']['count'] = $count;
}

当我尝试调试foreach中的$company时,一切都很好并且存储了计数。但是,当我返回整个$companies数组时,count不会存储。

非常感谢任何指导。

3 个答案:

答案 0 :(得分:10)

foreach适用于数组的副本。您可以改为使用引用:

foreach($companies as &$company) {
    $count = 3;
    $company['Company']['count'] = $count;
}
unset($company); // clear the reference

答案 1 :(得分:1)

Foreach适用于阵列的副本。您可以使用常规for循环:

for($i=0; $i < count($companies); $i++){

    $count = 3;
    $companies[$i]['Company']['count'] = $count;
}

答案 2 :(得分:1)

尝试这个更快。

foreach($companies as $key=>$company) {
    $count = 3;
    $companies[$key]['Company']['count'] = $count;
}