PHP。如何为新数组提取数组键?

时间:2012-07-19 17:53:06

标签: php arrays

如何从此数组中提取server_vps_de_dc1_s1

$server = array(    
    "vps" => array (        
        "de" => array (     
            "dc1" => array (                
                "s1" => array (                 
                    "name"=>    "Xen VPS 200",
                    "processor"=>   "200 MHz",
                    "memory"=>  "200 MB",
                ),                  
            ),              
        ),              
    ),              
    "dedicated" => array (      
        ...
    ),    
);

构建一个看起来像这个的新数组:

$server_id = array(    
    "1" => "server_vps_de_dc1_s1",
    "2" => "server_vps_de_dc1_s2",
    "3" => "server_vps_de_dc2_s1",
    "4" => "server_vps_usa_dc1_s1",
    ...
);

1 个答案:

答案 0 :(得分:1)

你需要递归:

function get_keys( $array)
{
    if( !is_array( $array)) 
        return array();
    $k = key( $array);
    return array_merge( array( $k), get_keys( $array[$k]));
}

你会这样调用它:

$keys = get_keys( $array);
array_pop( $keys); // Get rid of the last key:

你得到输出:

array(4) { [0]=> string(3) "vps" [1]=> string(2) "de" [2]=> string(3) "dc1" [3]=> string(2) "s1" } 

您可以使用implode()形成新值:

$new_value = implode( '_', $keys); // Outputs "vps_de_dc1_s1"

Demo