I dont have specified number of arrays, but they look like this:
array(("john","alex","tyler"),("1","2","3"),("brown","yellow","green"));
Example has 3 sub arrays, but the problem is this number can change.
As a final output i need, in this example, array with 3 strings.
array("john,1,brown","alex,2,yellow","tyler,3,green");
I'v tried the build in functions, still no satisfying solution.
The solution using call_user_func_array
, array_map
and array_merge
functions:
$arr = [["john","alex","tyler"],["1","2","3"],["brown","yellow","green"]];
$groups = call_user_func_array("array_map", array_merge([null], $arr));
$result = array_map(function ($v) {
return implode(",", $v);
}, $groups);
print_r($result);
The output:
Array
(
[0] => john,1,brown
[1] => alex,2,yellow
[2] => tyler,3,green
)
Here we are changing values of an array by converting array rows into columns. then imploding each array with comma (,
) Example: array[1][0]
will become array[0][1]
etc
<?php
$array=array(
array("john","alex","tyler"),
array("1","2","3"),
array("brown","yellow","green")
);
$result=array();
for($x=0;$x<count($array);$x++)
{
for($y=0;$y<count($array[$x]);$y++)
{
$result[$x][$y]=$array[$y][$x];//changing array values
}
}
foreach($result as $key => $value)
{
$result[$key]= implode(",", $value);//combining array values on comma(,)
}
print_r($result);
Output:
Array
(
[0] => john,1,brown
[1] => alex,2,yellow
[2] => tyler,3,green
)
Simpler approach using argument unpacking (php 5.6+)
<?php
$array = array(array("john","alex","tyler"),array("1","2","3"),array("brown","yellow","green"));
$result = array_map(function(...$elements) { return implode(",", $elements); }, ...$array);
print_r($result);
Same result as other replies.
Here is what is going on in a bit more detail:
array_map(/* anonymomous function */, ...$array);
...$array
takes the nested array and unpackes it, like you would call
array_map(/* anonymomous function */, $array[0], $array[1], ... $array[n])
array_map may take multiple arrays and apply the given callable to each round.
While the anonymous function more or less does the inverse
function(...$elements) { return implode(",", $elements); }
...$elements
takes an arbitrary amount of parameters and turns them into one array, which is then joined into one string.
@ultradurable3 this can be also done array_column() here you don't have to worry about the number of sub arrays, try like below:
<?php
$array = array(array("john","alex","tyler"), array("1","2","3"), array("brown","yellow","green"));
$finalArr = array(implode(",", array_column($array, 0)), implode(",", array_column($array, 1)), implode(",", array_column($array, 2)));
echo "<pre>";
print_r($finalArr);