我没有指定数量的子数组,但是我的数据结构看起来像这样:
array(("john","alex","tyler"),("1","2","3"),("brown","yellow","green"));
上面的示例有3个子数组,但问题是此数字可以更改。
作为最终输出,在此示例中,我需要一个包含3个字符串的数组。
array("john,1,brown","alex,2,yellow","tyler,3,green");
我尝试用函数编写此函数,但找不到解决方案。
使用call_user_func_array
,array_map
和array_merge
功能的解决方案:
$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);
输出:
Array
(
[0] => john,1,brown
[1] => alex,2,yellow
[2] => tyler,3,green
)
使用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);
与其他回复相同。
这里是更详细的内容:
array_map(/* anonymomous function */, ...$array);
...$array
提取嵌套数组并将其解包,就像您要调用
array_map(/* anonymomous function */, $array[0], $array[1], ... $array[n])
[array_map可以采用多个数组,并将给定的可调用项应用于每个回合。
而匿名函数或多或少地相反
function(...$elements) { return implode(",", $elements); }
[...$elements
接受任意数量的参数,并将它们变成一个数组,然后将其连接成一个字符串。
这里我们通过将数组行转换为列来更改数组的值。然后用逗号(,
)插入每个数组。例如:array[1][0]
将变为array[0][1]
等
<?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);
输出:
Array
(
[0] => john,1,brown
[1] => alex,2,yellow
[2] => tyler,3,green
)
@@ ultradurable3这也可以完成array_column(),这里您不必担心子数组的数量,请尝试如下操作:
<?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);