How can this task be accomplished? The goal is to get array3. The first array of each element contains the ID of this element. The second array of an unknown number of elements contains IDs identical to those from the first array. How can I make the elements of the second array nested in the ID elements of the first?

<? $array1 = array( [0] => array( 'id' => 1 ), [1] => array( 'id' => 2 ), [n] => array( 'id' => n ), ); ?> <? $array2 = array( [0] => array( 'target_id' => 1 ), [1] => array( 'target_id' => 2 ), [2] => array( 'target_id' => 1 ), [3] => array( 'target_id' => n ), ); ?> <? $array3 = array( [0] => array( 'id' => 1, 'children' => array( [0] => array( 'target_id' => 1 ), [1] => array( 'target_id' => 1 ) ) ), [1] => array( 'id' => 2, 'children' => array( [0] => array( 'target_id' => 2 ) ) ), [n] => array( 'id' => n, 'children' => array( [0] => array( 'target_id' => n ) ) ), ); ?> 
  • And specifically? Explain more fully what you want to achieve. - Sergey
  • $array3 - what should it look like? - Evgeny Nikolaev
  • I apologize for not immediately adding a description. Attached to the task - Anton Pomozov

2 answers 2

 $array1 = [ ['id'=>1], ['id'=>2], ]; $array2 =[ ['target_id' => 1], ['target_id' => 2], ['target_id' => 1] ]; $array3 = []; foreach($array1 as $elem){ $elem['children'] = array_filter($array2, function($item) use($elem){ return $item['target_id']== $elem['id']; }); $array3[] = $elem; } 
     $arr1 = [['id' => 1], ['id' => 2], ['id' => 5]]; $arr2 = [['target_id' => 1], ['target_id' => 2], ['target_id' => 1], ['target_id' => 5]]; foreach ($arr2 as $key => $value) { $new[$value['target_id']][] = $value; } $x = array_map(function($a, $b) { return ['id' => $a['id'], 'children' => $b]; }, $arr1, $new); print_r($x); 
    • Thank you, this option is also suitable. - Anton Pomozov