Showing posts with label array. Show all posts
Showing posts with label array. 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>";

Wednesday, May 8, 2019

selection by array


Hello

Here I display : Call one query one time. Save its value in array. Fetch it whenever need it.

/*get stage types*/
$stgsql = "SELECT * FROM stage_t";
$stgrs  = mysql_query($stgsql);
$stageTypes=array();
while($rowStage=mysql_fetch_assoc($stgrs))
  $stageTypes[$rowStage[code]]=$rowStage[edesc];

echo  $todaysstage = $stageTypes[$row[todaysstage]];