Home > database >  Concatenate value elements of two or more different arrays in PHP
Concatenate value elements of two or more different arrays in PHP

Time:11-25

I originally have this array

Array
(
    [0] => Amministrativo ^25^9,11,2,10,18,4,7,^17,13,^0.75^0^0.25
    [1] => Logico deduttive^7^^21,^0.75^0^-0.25
    [2] => Situazionali^8^^20,^0.75^0^0.375
)

Using the function explode and array_diff i can get to this

Array
(
    [0] => Amministrativo 
    [1] => 25
    [2] => 9,11,2,10,18,4,7,
    [3] => 17,13,
    [4] => 0.75
    [5] => 0
    [6] => 0.25
)
Array
(
    [0] => Logico deduttive
    [1] => 7
    [2] => 
    [3] => 21,
    [4] => 0.75
    [5] => 0
    [6] => -0.25
)
Array
(
    [0] => Situazionali
    [1] => 8
    [2] => 
    [3] => 20,
    [4] => 0.75
    [5] => 0
    [6] => 0.375
)

but I would like to concatenate the elements of each array to get a unique array. I think I need to use the array_map function but I don't know how. This below is the result I would like to achieve

Array (
[0] => Amministrativo Logico deduttive Situazionali
[1] => 25 7 8 
[2] => 9,11,2,10,18,4,7,
[3] => 17,13,21,20,
[4] => 0.75 0.75 0.75
[5] => 0 0 0
[6] => 0.25 -0.25 0.375
)

tnks


EDIT: I tried the code that is here and it is fine. But now I realized that there is also the problem that the arrays can be in variable number 1, 2, 3 or more and I can't know it before, I should adapt this code

$result = array_map(function ($item1, $item2,$item3) {
                                return "$item1 $item2 $item3";
                            }, $test[0], $test[1],$test[2]);

CodePudding user response:

The lines of the original array are split with explode. The result is a two-dimensional array. This is transposed (swapping rows and columns). Then the lines are reassembled with implode.

function array_transpose(array $a) {
  $r = array();
  foreach($a as $keyRow => $subArr) {
    foreach($subArr as $keyCol => $value) $r[$keyCol][$keyRow] = $value;
  }
  return $r;
}

$arr = [
 'Amministrativo ^25^9,11,2,10,18,4,7,^17,13,^0.75^0^0.25',
 'Logico deduttive^7^^21,^0.75^0^-0.25',
 'Situazionali^8^^20,^0.75^0^0.375',
];
    
foreach($arr as $i => $row){
  $arr[$i] = explode('^',$row);
}

$arr = array_transpose($arr);

foreach($arr as $i => $row){
  $arr[$i] = implode(' ',$row);
}

var_export($arr);

Demo: https://3v4l.org/IdsDh

  • Related