简体   繁体   中英

Is there any way to index an array with a sequence of indexes in a variable in PHP?

Having: an array $a, a variable $indexes = "[\\"level1\\"][\\"level2\\"][\\"level3\\"]" ;

Is there any way to access $a["level1"]["level2"]["level3"] ?

The situation is that the number of indexes that this function will handle can change. So this is the reason the indexes comes in a variable.

Hope this simple solution will help you out.

Try this code snippet here

<?php

ini_set('display_errors', 1);

//Here we are retrieving levels
$indexes = '["level1"]["level2"]["level3"]';
preg_match_all('/(?<=")[\w]+(?=")/', $indexes,$matches);
$levels=$matches[0];

//this is the sample array
$array=$tempArray=array(
    "level1"=>array(
        "level2"=>array(
            "level3"=>"someValue"
        )
    )
);
//here we are iterating over levels to get desired output.

foreach($levels as $level)
{
    $tempArray=$tempArray[$level];
}
print_r($tempArray);

Firstly, do not use string for $indexes , use an array .

For simple retrieving, you can use array_reduce :

$result = array_reduce($indexes, function ($array, $index) {
    return isset($array[$index]) ? $array[$index] : null;
}, $array);

Note that value defaults to null when there is no such index in the array.

Here is working demo .

If you want some more sophisticated stuff, check out a library I wrote some time ago for situations, when you also need to add items to an array and check for the existence:

var_dump(isset($array[['foo', 'bar']]));

var_dump($array[['foo', 'bar']]);

$array[['foo', 'bar']] = 'baz';

unset($array[['foo', 'bar']]);

They are all valid usage examples for existence checking, retrieving the element, writing the element and deleting the element respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM