Showing posts with label array key name with space. Show all posts
Showing posts with label array key name with space. Show all posts

Thursday, August 26, 2021

Fetch data from array using index key name

 After a long time I write a post.

See this array :-

$data = array (

    "key 1" => "a bc",

    "key 2" => array ("sub 1" => "ab c", "sub 2" => "def"),

    "key 3" => "gh i"

);

key name is with some space. So you can not use it directly by its key name.

One solution:-

foreach ($load_data as $key=>$value) {

                $fname = $value->{"First Name"};

$lname = $value->{"Last Name"};

}

you can use curly brackets {} with "" double quote.

Second method:-

function fixArrayKey(&$arr)

{

    $arr = array_combine(

        array_map(

            function ($str) {

                return str_replace(" ", "_", $str);

            },

            array_keys($arr)

        ),

        array_values($arr)

    );


    foreach ($arr as $key => $val) {

        if (is_array($val)) {

            fixArrayKey($arr[$key]);

        }

    }

}


$data = array (

    "key 1" => "a bc",

    "key 2" => array ("sub 1" => "ab c", "sub 2" => "def"),

    "key 3" => "gh i"

);

echo "<pre>";print_r($data);echo "</pre>";

echo "<hr>";


fixArrayKey($data); 


echo "<pre>";print_r($data); echo "</pre>";