How do I generate $i so that the first foreach fills $artRows like this:
array(1 => array(2, 'id1', 'title1'), 2 => array(2, 'id2', 'title2'), 3 => ...); And the second foreach is of the same type, only its first iteration should continue the account $ i, as if to start adding elements to the end.

  $artRows = array(); foreach ($rows2 as $row2) { $artRows[$i]['tbl'] = 2; $artRows[$i]['id'] = $row2['id']; $artRows[$i]['title'] = $row2['title']; } foreach ($rows as $row) { $artRows[$i]['tbl'] = 1; $artRows[$i]['id'] = $row['id']; $artRows[$i]['title'] = $row['title']; } 
  • It’s not clear where your problems are. More importantly, why all this. Maybe these all the elements can be stored in the same array with the same keys. (1 => ['id' = 1, 'title' = '1'], 2 => ['id' = 2, 'title' = '2']); - Makarenko_I_V
  • Well, make a counter, which will be added within the first cycle, and then apply it in the second cycle ...... but in general you can do everything in one cycle through for where in one array it will be added with the index $i , and in the other $i + count($arr1) - 1; Although sure you can still do something easier, depending on the task .... I am sure you are building a crutch - Alexey Shimansky

2 answers 2

Create the $ i variable with the first array key you need and increment it at the end of the loops.

 $artRows = array(); $i = 1; foreach ($rows2 as $row2) { $artRows[$i]['tbl'] = 2; $artRows[$i]['id'] = $row2['id']; $artRows[$i]['title'] = $row2['title']; $i++; } foreach ($rows as $row) { $artRows[$i]['tbl'] = 1; $artRows[$i]['id'] = $row['id']; $artRows[$i]['title'] = $row['title']; $i++; } 

If it is not necessary to skip filling the zero key, then it is best to use the standard php function array_merge ();

     $i = 1; $artRows = []; foreach ($rows2 as $row2) { $tmp = [ 'tbl' => 2, 'id' => $row2['id'], 'title' => $row2['title'] ]; $artRows[ $i++ ] = $tmp; } foreach ($rows as $row) { $tmp = [ 'tbl' => 1, 'id' => $row['id'], 'title' => $row['title'] ]; $artRows[ $i++ ] = $tmp; } 
    • corrected, will start from 1 and not from 0. - Arnial