Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from nested array using string

I have an array like this:

$temp = array( '123' => array( '456' => array( '789' => '0' ) ),
               'abc' => array( 'def' => array( 'ghi' => 'jkl' ) )
             );

I have a string like this:

$address = '123_456_789';

Can I get value of $temp['123']['456']['789'] using above array $temp and string $address?

Is there any way to achieve this and is it good practice to use it?

like image 732
Awan Avatar asked Dec 24 '22 13:12

Awan


2 Answers

This is a simple function that accepts an array and a string address where the keys are separated by any defined delimiter. With this approach, we can use a for-loop to iterate to the desired depth of the array, as shown below.

<?php
function delimitArray($array, $address, $delimiter="_") {
    $address = explode($delimiter, $address);
    $num_args = count($address);

    $val = $array;
    for ( $i = 0; $i < $num_args; $i++ ) {
        // every iteration brings us closer to the truth
        $val = $val[$address[$i]];
        }
    return $val;
    }

$temp = array("123"=>array("456"=>array("789"=>"hello world")));
$address = "123_456_789";
echo delimitArray($temp,$address,"_");
?>
like image 55
Typel Avatar answered Jan 03 '23 21:01

Typel


Hello if string $address = '123_456_789'; is your case then you can use explode function to split the string by using some delimeter and you can output your value

<?php
$temp = array('123' => array('456' => array('789' => '0')),
    'abc' => array('def' => array('ghi' => 'jkl')),
);
$address = '123_456_789';
$addr = explode("_", $address);
echo $temp[$addr[0]][$addr[1]][$addr[2]];
like image 27
Samundra Khatri Avatar answered Jan 03 '23 21:01

Samundra Khatri