如何组合多个数组

时间:2013-04-20 14:48:04

标签: php arrays

首先关于这个question的问题。我的问题是我的一个朋友有大约300个左右的数组,她需要插入到数据库中。我收到数据库部分正如你在我链接的问题中注意到的那样,我有那个部分。然而,我的问题出现在我应该如何获得所有数组并将它们组合在一起以便我可以在数组上做一个foreach并检查一个值是否是一个数组,如果是,则使用数组名称作为INSERT查询中的表。

这是我更新的代码:

        $colors['Colors_All'] = array("Black","Charcoal"); // Add unique indexes 
        $colors['Colors_Bright_All'] = array("Silver","White"); // Add unique indexes 

        $AllArrays = get_defined_vars(); // Get all defined vars
        $Arrays = array(); // Set a default array

        foreach ($AllArrays as $varName => $value) { // Run through all the variables set in the get_defined_vars
            if(is_array($value) && $varName == 'colors') { // If it is an array and if the array is colors[] then
                $Arrays = array_merge($Arrays, $value); // Merge those arrays into the new array
            }
        }

现在可以访问所有数据。

1 个答案:

答案 0 :(得分:2)

你走了:

$colors['Colors_All']        = array("Black","Charcoal","Light_Gray","Silver","White","Gold","Bronze","Copper","Platinum","Navy","Royal_Blue","Dodger_Blue","Deep_Sky_Blue","Turquoise","Tiffany_Blue");
$colors['Colors_Bright_All'] = array("Silver","White","Gold","Royal_Blue","Dodger_Blue","Deep_Sky_Blue","Deep_Green","Forest_Green","Bright_Green","Violet");
$colors['Colors_Light_All']  = array("Light_Gray","Silver","White","Gold","Dodger_Blue","Deep_Sky_Blue","Light_Blue","Bright_Green","LightGreen","Light_Green");

// This will store the merged results of each array
$colorVars = array();

// Loop through all of the defined variables
foreach ($colors as $colorKey => $value) {
    // Add the results of this array to the main $colorVars array
    $colorVars = array_merge($colorVars, $value);
}