if inside for each loop pushing multidimensional array - php -


i'm running 2 each loops , pushing 1 of them other one. works fine, except if have more 1 match. in case, i'm getting last one. sorry title, not sure how call question in 1 line.

foreach($items &$item) {     foreach($fruits &$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 if($fruit['for']==$item['id']) logic, i'd 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 doing wrong?

you set $i 0 every array-element check. renders $i++ useless , first match gets overwritten. try either this:

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

or this: (depending on need)

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

that way, each time find new match gets new key.


Comments