0

I'm using array_push to add values to a multidimensional array.

My code looks like:

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 holds:

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

)

$filter is to big to post here, but it's an array with product ID's and the filter key key_value.

Now when I run this code, it's output is:

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)

The $tmp array however looks like this:

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
)

All productID's should be in tmp[4], but why are they also just in tmp?

3
  • Could you show a couple values inside $filter? Commented Apr 1, 2014 at 10:14
  • I don't think the issue is in the code that you have shown. Are you sure that $tmp itself is empty when you start? Commented Apr 1, 2014 at 10:15
  • The problem was that $tmp was not an array! Commented Apr 1, 2014 at 10:32

1 Answer 1

1

This is not really an answer, but it was too big for a comment.

I don't know why or how, but your $tmp contained the following when your loop started:

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
)

Make sure that $tmp is an empty array when you start.

Sign up to request clarification or add additional context in comments.

1 Comment

That was the fix. Just missed it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.