Peon
Peon

Reputation: 8020

Add params to array request

I have a pretty large array that I would need to parse, but the request changes depending on enabled/disabled parameters.

For example:

$array['a'][1]['b'][1]['c'][1] = 'asd';
$str = $array['a'][1];

dd($str);

This would give me:

Array
(
    [b] => Array
    (
        [1] => Array
        (
            [c] => Array
            (
                [1] => asd
            )

        )

    )

)

Which, of course, is correct. But now, if I know, that I need also the next parameter, I would need to add that like $str = $array['a'][1]['b'];.

But since there are way too many combinations, I wondered, if I can construct the call manually, something like this":

$str = $array['a'][1];
if ($b) {
    $str .= ['b'][1];
}
if ($c) {
    $str .= ['c'][1];
}

dd($str);

Any hints will be appreciated.

PS: I know I can do this with eval, but was really looking for a better solution:

eval("\$str = \$array$str;");
dd($str);

Upvotes: 0

Views: 65

Answers (1)

splash58
splash58

Reputation: 26153

It can be done with Reference

$string = "['a'][1]['b'][1]";
// Maybe, not optimal, but it's not the point of the code
preg_match_all('/\[\'?([^\]\']+)\'?\]/', $string, $steps);

// "Root" of the array
$p = &$array;

foreach($steps[1] as $s) {
     // Next step with current key  
     if (isset($p[$s]) && is_array($p)) $p = &$p[$s];
     else throw new Exception("No such item");
} 
// Target value
$str = $p;

demo

Upvotes: 2

Related Questions