如何合并具有相同键的所有嵌套数组值

时间:2016-04-27 07:31:52

标签: php

我有一个像这样的数组,

Array
(
    [0] => Array
        (
            [0] => m_res1
            [1] => m_res2
        )

    [1] => Array
        (
            [0] => images
            [1] => pcgc_desc
            [2] => The_US_GRANT_A_Luxury_Collection_Hotel_usn_2
        )

    [2] => Array
        (
            [0] => Australis
        )

    [3] => Array
        (
            [0] => Greece
            [1] => download
        )

    [4] => Array
        (
            [0] => Studio
        )

)

我想这样......

Array
(
    [0] => m_res1
    [1] => m_res2
    [2] => images
    [3] => pcgc_desc
    [4] => The_US_GRANT_A_Luxury_Collection_Hotel_usn_2
    [5] => Australis
    [6] => Greece
    [7] => download
    [8] => Studio
)

即:合并嵌套数组值并将其作为一个数组...

这可能吗?

3 个答案:

答案 0 :(得分:1)

您可以执行类似的操作将关联数组转换为普通数组

// Here $arr is your original array
$result_array = call_user_func_array('array_merge', $arr);

// display $result_array
echo "<pre>";
print_r($result_array);
echo "</pre>";

输出:

Array
(
    [0] => m_res1
    [1] => m_res2
    [2] => images
    [3] => pcgc_desc
    [4] => The_US_GRANT_A_Luxury_Collection_Hotel_usn_2
    [5] => Australis
    [6] => Greece
    [7] => download
    [8] => Studio
)

以下是相关参考资料:

答案 1 :(得分:1)

您可以使用Standard PHP Library (SPL)如果原始数组的深度高于2级,则PHP中的SPL会有一个RecursiveArrayIterator,您可以使用它来展平它:

$finalArray = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($a)); //$a is your multidimentional original array
foreach($iterator as $v) {
    $finalArray[] = $v;
}
echo "<pre>";
print_r($finalArray);  //print your array
echo "</pre>";

输出

Array
(
    [0] => m_res1
    [1] => m_res2
    [2] => images
    [3] => pcgc_desc
    [4] => The_US_GRANT_A_Luxury_Collection_Hotel_usn_2
    [5] => Australis
    [6] => Greece
    [7] => download
    [8] => Studio
)  

注意:或者,您可以使用call_user_func_array('array_merge', $a);展平您的阵列,但它只适用于 2级深度

解释:

$a = Array(
    Array("m_res1","m_res2"),
    Array("images","pcgc_desc","The_US_GRANT_A_Luxury_Collection_Hotel_usn_2"),
    Array("Australis"),
    Array("Greece","download"),
    Array("Studio"),
    Array(
        Array("3rd Level")
        )
    );

$finalArray = call_user_func_array('array_merge', $a);

echo "<pre>";
print_r($finalArray);  //print your array
echo "</pre>";

输出

Array
(
    [0] => m_res1
    [1] => m_res2
    [2] => images
    [3] => pcgc_desc
    [4] => The_US_GRANT_A_Luxury_Collection_Hotel_usn_2
    [5] => Australis
    [6] => Greece
    [7] => download
    [8] => Studio
    [9] => Array
        (
            [0] => 3rd Level
        )

)

答案 2 :(得分:1)

像这样使用

$main = array();
foreach($arr as $key => $arrsub)
{
    foreach($arrsub as $key => $value)
    {
        array_push($main,$value);
    }
}
echo "<pre>";
print_r($main);
echo "</pre>";

了解有关array_push

的更多信息

http://php.net/manual/en/function.array-push.php