Home > Enterprise >  Append each item of arrays to a new array
Append each item of arrays to a new array

Time:04-17

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);
}

CodePudding user response:

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 :)

  • Related