There are two arrays:

Array ( [0] => Array ( [y] => 67 [product_id] => 0 [product_type] => 3 ) [1] => Array ( [y] => 30 [product_id] => 3 [product_type] => 2 ) [2] => Array ( [y] => 17 [product_id] => 2 [product_type] => 2 ) [3] => Array ( [y] => 23 [product_id] => 1 [product_type] => 2 ) ) 

Second array

 Array ( [0] => Array ( [title] => Title 1 [id] => 1 ) [1] => Array ( [title] => Title 2 [id] => 3 ) [2] => Array ( [title] => Title 3 [id] => 2 ) ) 

I need to check if the [product_id] of the first array matches the [id] of the second array, then add [type] => [id] [title] - the second array to the first array.

I do this as follows: 1. I count the length of the array 2. 2. I run for while $ i <Array length 2 3. Compare $ i [product_id] and $ i [id] 4. If it is the same, I write down the value. It works, but it works only 3 times, because the second array is 3 long, and the first one is longer, therefore it does not calculate everything. How to be in this case?

  • Does the position of the element in the array matter? Those. need to check only the presence or even the coincidence of the indices? - Igor Karpenko
  • It is only necessary that all [product_id] of the first array with [id] of the second array be checked for matches - Fitstd

3 answers 3

 array_walk( $array1, function (&$item1, $key) use ($array2) { // параметры value, key if ($item1['product_id'] == $array2[$key]['id']) { $item1['type'] = $array2[$key]['title'] } }); 

The array_walk function passes through the array $ array1 and executes the function passed by the 2nd parameter on the array elements

     foreach ($array1 as $pos => $item) { foreach ($array2 as $title) { if ($item['product_id'] == $title['id']) { $array1[$pos]['title'] = $title['title']; } } } 
       foreach ($a as $key=>$val){ foreach($b as $k=>$v['id']){ if( $val['product_id'] === $v){ $a[$key]['type'] = $v['title']; } } }