将两个阵列组合在一起

时间:2016-02-17 09:23:49

标签: php arrays

我有一个如下所示的数组:

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 
        )
)

2 个答案:

答案 0 :(得分:3)

<强>更新

对于当前数组,您需要使用循环。

$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&gt; = 5.5

或者你可以尝试 -

$first = $second = array();
foreach($yourArray as $array) {
    $first[] = $array[0];
    $second[] = $array[1];
}
$final['together'] = array($first, $second);

答案 1 :(得分:0)

您也可以尝试array_map,如下所示

function merge($first,$second)
{
	return $first ." ".$second; 
}
$combine = array_map('merge', $yourArray[0],$yourArray[1]);