简体   繁体   中英

if inside for each loop pushing multidimensional array - php

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?

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++;
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM