Thursday, 30 August 2018

PHP Prefer a multidimensional associative array

I have a multidimensional associative array:
array(
        "X" => array( "x1" => "1", "x2" => "2", "x3" => "3" ),
        "Y" => array( "y1" => "1", "y2" => "2", "y3" => "3" ),
        "Z" => array( "z1" => "1", "z2" => "2", "z3" => "3" )
)

and need to prepend "" => "" to every element X, Y, Z, so then it will be:
array(
            "X" => array( "" => "", "x1" => "1", "x2" => "2", "x3" => "3" ),
            "Y" => array( "" => "", "y1" => "1", "y2" => "2", "y3" => "3" ),
            "Z" => array( "" => "", "z1" => "1", "z2" => "2", "z3" => "3" )
)

X, Y, Z names are often changed, so I need to get a key name first and then add new value.
I think of using foreach somehow. I'm trying it, but can achieve it.
Thanks

 <?php
    $temp = array(
       "X" => array( "x1" => "1", "x2" => "2", "x3" => "3" ),
       "Y" => array( "y1" => "1", "y2" => "2", "y3" => "3" ),
       "Z" => array( "z1" => "1", "z2" => "2", "z3" => "3" )
    );
    $you_array = array();
    foreach($temp  as $k=>$v){

       $v = array_merge([""=>""],$v);
       $you_array[$k] = $v;
    }
    print_r($you_array);
 ?>

0 comments:

Post a Comment