数组推入多维数组也推入数组

时间:2014-04-01 10:08:25

标签: php arrays multidimensional-array

我使用array_push为多维数组添加值。

我的代码如下:

foreach($arr as $key => $subArr){
  $tmp[$key] = array();

  foreach($subArr as $value){
    foreach($filter as $prod){
      if($prod['key_value'] == $key."_".$value){
        echo "array_push(tmp[{$key}], {$prod['id']})<br>";
        array_push($tmp[$key], $prod['id']);
      }
    }
  }
}

$arr持有:

Array
(
    [4] => Array
        (
            [0] => 821
        )

)

$filter在此处发布很重要,但它是一个包含产品ID和过滤器密钥key_value的数组。

现在,当我运行此代码时,它的输出是:

array_push(tmp[4], 180)
array_push(tmp[4], 172)
array_push(tmp[4], 182)
array_push(tmp[4], 116)
array_push(tmp[4], 170)
array_push(tmp[4], 169)
array_push(tmp[4], 144)
array_push(tmp[4], 145)
array_push(tmp[4], 187)
array_push(tmp[4], 124)
array_push(tmp[4], 198)
array_push(tmp[4], 148)
array_push(tmp[4], 163)
array_push(tmp[4], 195)
array_push(tmp[4], 194)
array_push(tmp[4], 196)

$tmp数组看起来像这样:

Array
(
    [0] => 180
    [1] => 172
    [2] => 182
    [3] => 116
    [4] => Array
        (
            [0] => 180
            [1] => 172
            [2] => 182
            [3] => 116
            [4] => 170
            [5] => 169
            [6] => 144
            [7] => 145
            [8] => 187
            [9] => 124
            [10] => 198
            [11] => 148
            [12] => 163
            [13] => 195
            [14] => 194
            [15] => 196
        )

    [5] => 169
    [6] => 144
    [7] => 145
    [8] => 187
    [9] => 124
    [10] => 198
    [11] => 148
    [12] => 163
    [13] => 195
    [14] => 194
    [15] => 196
)

所有产品ID应该在tmp[4],但为什么它们也只在tmp

1 个答案:

答案 0 :(得分:1)

这不是一个真正的答案,但它对评论来说太大了。

我不知道原因或方法,但您的$tmp在您的循环开始时包含以下内容:

Array
(
    [0] => 180
    [1] => 172
    [2] => 182
    [3] => 116
    [4] => 170
    [5] => 169
    [6] => 144
    [7] => 145
    [8] => 187
    [9] => 124
    [10] => 198
    [11] => 148
    [12] => 163
    [13] => 195
    [14] => 194
    [15] => 196
)

启动时确保$tmp数组。