0

I'm running two for each loops and pushing one of them into the other one. This works fine, except if my I have more than one match. In that case, I'm only getting the last one. Sorry about the title, not too sure how to call this question in one line.

foreach($items as &$item) {
    foreach($fruits as &$fruit) {
        $i = 0;
        if($fruit['for']==$item['id']) {
            $item["fruits"][$i] = $fruit;
            $i++;
        }
    }
}

First array :

array(114) {
  [0]=>
  array(5) {
    ["id"]=>
    string(2) "76"
    ...
  }
...
}

Second array :

array(47) {
  [0]=>
  array(5) {
    ["id"]=>
    string(1) "4"
    ["for"]=>
    string(2) "76"
    ...
  }
  ...
}

With multiple matches of the if($fruit['for']==$item['id']) logic, I'd like the following output.

array(114) {
  [0]=>
  array(6) {
    ["id"]=>
    string(2) "76"
    ...
    ["fruits"]=>
    array(2) {
      [0]=>
      array(5) {
        ["id"]=>
        string(1) "4"
        ["for"]=>
        string(2) "76"
        ...
      }
      [1]=>
      array(5) {
        ["id"]=>
        string(2) "33"
        ["for"]=>
        string(2) "76"
        ...
      }
    }
  }
}

What am I doing wrong?

2 Answers 2

2

take $i outside the loop, your match is always stored in $item["fruits"][0]

foreach($items as &$item) {
    $i = 0;   
    foreach($fruits as &$fruit) {
        if($fruit['for']==$item['id']) {
            $item["fruits"][$i] = $fruit;
            $i++;
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

$i = 0; inside the first loop is the result I want, but thanks for pointing me in the right direction :)
1

You set $i to 0 for every array-element you check. This renders the $i++ useless and your first match gets overwritten. Try either this:

foreach($items as &$item) {
    $i = 0;
    foreach($fruits as &$fruit) {
        if($fruit['for']==$item['id']) {
            $item["fruits"][$i] = $fruit;
            $i++;
        }
    }
}

or this: (depending on what exactly you will need)

$i = 0;
foreach($items as &$item) {
    foreach($fruits as &$fruit) {
        if($fruit['for']==$item['id']) {
            $item["fruits"][$i] = $fruit;
            $i++;
        }
    }
}

That way, each time you find a new match it gets a new key.

1 Comment

so that was it.... thank you! I'm not sure how to feel, proud that I'm getting so close (php is new to me), or sad that I didn't see my error. Thank you very much!

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.