为什么 foreach 数组没有按预期执行并且没有生成所需的输出?我犯了什么错误?

Why the foreach array is not executing as expected and not generating the desired output? What mistake I'm making?

我有一个名为 $allFeeds 的大数组,如下所示:

Array
(
[custom_data_cache] => Array
        (
[answer] => Array
                (
                    [0] => Array
                        (
                            [answer_id] => 289
                            [poll_id] => 115
                            [answer] => Let's meet now
                            [total_votes] => 0
                            [ordering] => 1
                            [vote_percentage] => 0
                        )

                    [1] => Array
                        (
                            [answer_id] => 290
                            [poll_id] => 115
                            [answer] => Let's plan sometime later
                            [total_votes] => 0
                            [ordering] => 2
                            [vote_percentage] => 0
                        )

                )

        )
)

我想在最里面的 ['answer'] 键中设置值,而不是外部 ['answer'] 键空白(在上面的数组中存在两个这样的元素)但我做不到。

以下是我试过的代码,但数组根本没有改变。

foreach ($allFeeds['custom_data_cache']['answer'] as $key => $value) {
      $key[$value]['answer'] = '';          
    }
print_r($allFeeds);

再次打印相同的数组。预期输出如下:

Array
(
[custom_data_cache] => Array
        (
[answer] => Array
                (
                    [0] => Array
                        (
                            [answer_id] => 289
                            [poll_id] => 115
                            [answer] => 
                            [total_votes] => 0
                            [ordering] => 1
                            [vote_percentage] => 0
                        )

                    [1] => Array
                        (
                            [answer_id] => 290
                            [poll_id] => 115
                            [answer] => 
                            [total_votes] => 0
                            [ordering] => 2
                            [vote_percentage] => 0
                        )

                )

        )
)

请帮助我纠正我在数组操作中犯的错误。

您的本地(用于循环)变量 $key 仅保存索引而不是对该索引下的元素(数组)的引用,并且 $value 保存 copy 该元素(数组)。赋值 $key[$value]['answer'] = ''; 在很多层面上都是错误的(语法上和语义上)。顺便说一句,你的 error_reporting 有没有关掉?
因此改变

foreach ($allFeeds['custom_data_cache']['answer'] as $key => $value) {
    $key[$value]['answer'] = '';          
}

foreach ($allFeeds['custom_data_cache']['answer'] as $key => $value) {
    $allFeeds['custom_data_cache']['answer'][$key]['answer'] = '';          
}

您可以轻松地将最里面的 answer 值设置为空字符串,如下所示:

foreach ($allFeeds['custom_data_cache']['answer'] as &$value) {
  $value['answer'] = '';          
}
print_r($allFeeds);

使用 &value 可以修改数组而无需重新遍历所有维度。