如何在php中将所有键值合并到一个数组中[重复]
Posted
技术标签:
【中文标题】如何在php中将所有键值合并到一个数组中[重复]【英文标题】:How to merge all key values into one in single array in php [duplicate] 【发布时间】:2017-12-13 22:21:43 【问题描述】:我有一个如下所示的数组值,
Array ( [0] => ["f","a","s","d"] [1] => ["d","b","a","c"] [2] => ["c"])
我也希望像下面提到的那样合并数组值
Array ( [0] => ["f","a","s","d","d","b","a","c","c"])
所有键值应合并到一个新的数组键下
【问题讨论】:
$merge = $arr[0] + $arr[1] + $arr[2];
是硬编码,可能是key loop增加了
【参考方案1】:
在 php 5.6 版本中,您可以使用更好的方法来做到这一点。 PHP 5.6 添加了解包数组的新功能,称为 splat operator (...):
$arr = Array (["f","a","s","d"],["d","b","a","c"],["c"]);
$result = array_merge(...$arr);
【讨论】:
【参考方案2】:您可以将初始数组作为参数传递给call_user_func_array
并使用array_merge
:
$arr = Array (["f","a","s","d"],["d","b","a","c"],["c"]);
print_r(call_user_func_array('array_merge', $arr));
对于支持可变参数的 php 版本(自 5.6 起),它更简单:
print_r(array_merge(...$arr));
【讨论】:
我不知道array_merge
聪明地知道它的唯一参数是嵌套数组而不是多参数数组样式。谢谢你的回答,但你为什么不直接调用函数array_merge($arr)
而不使用call_user_func_array
array_merge
合并数组。如果您将一个数组传递给它 - 它应该将该数组与合并什么?
抱歉,我误会了。我以为您将$arr
作为一个参数传递给array_merge
。【参考方案3】:
方式一:
$result = array_reduce($arr, 'array_merge', array());
方式二:
$result = call_user_func_array('array_merge', $arr);
方式3:
foreach ($arr as $key => $value)
array_merge($result,$value);
得到结果后,你必须做: 存储为字符串:
$tmp[] = implode(",",$result);
print_r($tmp);
or as array:
$tmp[] = result;
【讨论】:
所有方法都不起作用 使用 print_r($result) 检查 哦,对不起,我明白了 现在我当前的操作:Array ( [0] => ["184","188","201","263"] [1] => ["184","188" ,"201","263"] [2] => ["185"] [3] => ["201","202","204"]) 但我需要的是数组 ( [0] => ["184","188","201","263","184","188","201","263 ","185","201","202","204")【参考方案4】:您可以使用array_merge
http://php.net/manual/en/function.array-merge.php 合并数组,您可以在其中发送您拥有的数组数组
【讨论】:
它不起作用,arrray_merge 用于合并两个数组值【参考方案5】:按照您的建议使用循环。
$var = Array (["f","a","s","d"] ,["d","b","a","c"],["c"]) ;
$temp =[];
foreach ($var as $key => $value)
foreach ($value as $key_1 => $value_1)
array_push($temp, $value_1);
print_r([$temp]);
【讨论】:
以上是关于如何在php中将所有键值合并到一个数组中[重复]的主要内容,如果未能解决你的问题,请参考以下文章