0

How can I extract server_vps_de_dc1_s1 from this array:

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

to build new array that should looks like this one:

$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
  • 3
    You're going to have to use a lot of loops. You should consider refactoring your code; this looks suboptimal. Commented Jul 19, 2012 at 17:56

1 Answer 1

1

You'll need recursion:

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

You'd invoke it like this:

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

And you get as output:

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

Which you can form your new values with implode():

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

Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.