如何在循环中重新分配数组值?

时间:2016-05-09 11:53:50

标签: php arrays

我有以下代码: -

$returnArr = $this->master_model->fetch_all_data($data, $selectString,$limit, $offset);
foreach($returnArr as $row)
    {
        if (array_key_exists($data.'_image', $row)) 
        {
            $img = base_url()."uploads/$data/". $row[$data.'_image'];
            $row[$data.'_image'] = $img;
        }
    }
print_r($returnArr);

$ return的格式如下:

Array ( [0] => 
         Array ( [sticker_image] => post_1462515402.jpg 
                 [sticker_code] => :* ) 
        [1] => Array ( [sticker_image] => post_1462515510.jpg 
                 [sticker_code] => ^=^ ) 
        [2] => Array ( [sticker_image] => post_1462515532.jpg 
                 [sticker_code] => >_<* ) 
        [3] => Array ( [sticker_image] => post_1462515539.jpg 
                 [sticker_code] => :(( ) ) 

现在,在以下代码行中,我将[sticker_image]更改为链接:

if (array_key_exists($data.'_image', $row)) 
{
    $img = base_url()."uploads/$data/". $row[$data.'_image'];
    $row[$data.'_image'] = $img;
}

尽管如此,这些变化仍未发生。它仍然是

[sticker_image] => post_1462515402.jpg

我做错了什么?

1 个答案:

答案 0 :(得分:1)

$row[$data.'_image'] = $img;只会更改数组元素的本地副本。

要更改实际的数组元素,必须使用引用循环:

$returnArr = ['a' => 'b'];

foreach ($returnArr as &$row) {
    $row = 'cc';
}

var_dump($returnArr); // ['a' => 'cc'];