合并两个数组一起
我有一个数组,看起来像这样:合并两个数组一起
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
)
);
array_column
支持PHP> = 5.5
或者你可以尝试 -
$first = $second = array();
foreach($yourArray as $array) {
$first[] = $array[0];
$second[] = $array[1];
}
$final['together'] = array($first, $second);
谢谢,这工作,但是你介意解释第一个答案吗? 我的数组上面显示[first]和[second]实际上更像[name]和[description]。 那么这怎么知道我想结合哪些东西呢? –
你可以显示你的实际数组吗? –
当然我会更新我的问题 –
你也可以尝试array_map
如下
function merge($first,$second)
{
\t return $first ." ".$second;
}
$combine = array_map('merge', $yourArray[0],$yourArray[1]);
Downvote?它没有帮助吗? –
是它始终只是要两个指数?或者是否有* n *个索引,并且您希望将'first [n]'与'second [n]'(顺便说一句,这非常接近您需要的实际语法...)。 – deceze
它总是会以[first]和[second]出现,我需要将[first] [0]与[second] [0]相结合,依此类推。我知道如何用循环等来做到这一点......但我想看看是否有这样的功能,我可以使用 –
为什么不简单地连接它们,当它总是相同? –