Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
207 views
Welcome To Ask or Share your Answers For Others

1 Answer

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,"_");
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...