1

I have 4 different arrays with the same count of elements. I want to add each element of each array into a new array. For example: $id_array[0] should be added into $artikel_combined. Then $name_array[0] into $artikel_combined. And so on. Then when all 4 arrays are done with index 0, then they should start with index 1 and so on.

I tried with this code but it just combines all the arrays, but not what i want.

// LoadIni creates an array every nth line.
$id_array = $ini_obj->LoadIni($f_art, 0, 9, 999);
$name_array = $ini_obj->LoadIni($f_art, 1, 9, 999);
$x_array = $ini_obj->LoadIni($f_art, 2, 9, 999);
$y_array = $ini_obj->LoadIni($f_art, 4, 9, 999);

// This is the point where i fail, because it just combines and I'm out of ideas
$arr = array_merge($id_array, $name_array, $x_array, $y_array);
$artikel_combined = [];

// Removing new Lines from the elements
foreach ($arr as $item) {
    $artikel_combined[] = trim($item);
}
Discide
  • 13
  • 3

2 Answers2

1

if the array have always the same count of elements you can cycle through them and add them together.

like

$count = count($id_array);
$artikel_combined = [];

for($i=0;$i<$count;$i++){
    $artikel_combined[$i][] = id_array[$i];
    $artikel_combined[$i][] = trim(name_array[$i]);
    $artikel_combined[$i][] = trim(x_array[$i]);
    $artikel_combined[$i][] = trim(y_array[$i]);
}

probably not the best way to solve the problem, but it should do the job :)

0

Using array_merge: "Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one."

But you want to join up the same array key for every array into a new array, resulting in a multidimensional array.

You could also do so using array_map passing null as the first parameter:

// LoadIni creates an array every nth line.
$id_array = $ini_obj->LoadIni($f_art, 0, 9, 999);
$name_array = $ini_obj->LoadIni($f_art, 1, 9, 999);
$x_array = $ini_obj->LoadIni($f_art, 2, 9, 999);
$y_array = $ini_obj->LoadIni($f_art, 4, 9, 999);

$artikel_combined = array_map(null, $id_array, $name_array, $x_array, $y_array);
The fourth bird
  • 154,723
  • 16
  • 55
  • 70