Php 将两个阵列组合在一起
我有一个如下所示的数组:Php 将两个阵列组合在一起,php,arrays,Php,Arrays,我有一个如下所示的数组: array ( [name] => name [description] => description here [first] => Array ( [0] => weight [1] => height ) [second] => Array ( [0] => 20 kg
array
(
[name] => name
[description] => description here
[first] => Array
(
[0] => weight
[1] => height
)
[second] => Array
(
[0] => 20 kg
[1] => 50 cm
)
[company_id] => 1
[category_id] => 7
)
什么函数允许我将这些组合成如下所示的内容
array
(
[together]
(
[0] => weight 20kg
[1] => height 50cm
)
)
更新
对于当前阵列,需要使用循环
$first = $second = array();
foreach($yourArray as $key => $array) {
if(in_array($key, array('first', 'second')) {
$first[] = $array[0];
$second[] = $array[1];
}
}
$final['together'] = array($first, $second);
根据第一个数组
你可以试试这个-
$new = array(
'together' => array(
implode(' ', array_column($yourArray, 0)), // This would take out all the values in the sub arrays with index 0 and implode them with a blank space
implode(' ', array_column($yourArray, 1)), // Same as above with index 1
)
);
PHP>=5.5支持数组_列
或者你可以试试-
$first = $second = array();
foreach($yourArray as $array) {
$first[] = $array[0];
$second[] = $array[1];
}
$final['together'] = array($first, $second);
您也可以尝试如下所示的数组映射
函数merge$first,$second
{
返回$first..$second;
}
$combine=array_映射‘merge’,$yourArray[0],$yourArray[1];谢谢,这很有效,不过你介意解释一下第一个答案吗?上面显示[first]和[second]的数组实际上更像[name]和[description]。那么,这怎么知道我想合并哪些内容呢?我应该使用你更新的帖子而不是第一篇吗?它总是只有两个索引吗?或者有n个索引,你想把first[n]和second[n]结合起来,顺便说一句,这非常接近你需要的实际语法……它总是以[first]和[second]的形式出现,我需要把[first][0]和[second][0]结合起来,依此类推。我知道如何处理循环等。。。但是我想看看是否有一个函数可以用于此,为什么不简单地将它们连接起来,当它们总是相同的时候?