Home > Blockchain >  how to access array position from string
how to access array position from string

Time:10-21

I have a string containing an array key position which I am trying to use this position to access the array ($arr).

Example of string ($str) which has a string value of svg.1.linearGradient.0.@style

This would be the equivalent of ['svg'][1]['linearGradient'][0]['@style']

How can I use the string to access/retrieve data from $arr using the above position?

For example, lets say i wanted to unset the array key unset($arr['svg'][1]['linearGradient'][0]['@style']) - how can i achieve this programmatically?

CodePudding user response:

One method could be to split the string on ., then iterate through the "keys" to traverse your $arr object. (Please excuse my poor php, it's been a while...)

Example:

$arr = (object)[
    "svg" => (array)[
        (object)[],
        (object)[
            "linearGradient" => [
                (object)[
                    "@style" => "testing",
                ],
            ],
        ],
    ],
];

$str = "svg.1.linearGradient.0.@style";
$keys = explode('.', $str);
$val = $arr;
foreach($keys as $key) {
  $val =  is_object($val) 
    ? $val->$key 
    : $val[$key];
}

echo $val;

https://3v4l.org/h8YPv

Unsetting a key given the path:

$arr = (object)[
    "svg" => (array)[
        (object)[],
        (object)[
            "linearGradient" => [
                (object)[
                    "@style" => "testing",
                ],
            ],
        ],
    ],
];

$str = "svg.1.linearGradient.0.@style";
$keys = explode('.', $str);
$exp = "\$arr";
$val = $arr;
foreach($keys as $index => $key) {
    $exp .=  is_object($val) 
        ? "->{'" . $key . "'}"
        : "[" . $key . "]";
    
    $val = is_object($val) ? $val->$key : $val[$key]; 
}

eval("unset($exp);");

https://3v4l.org/Fdo6B

Docs

CodePudding user response:

You can use the mechanism of passing the value by reference:

$result = &$arr;
$path = explode('.', $str);

for($i = 0; $i < count($path); $i  ) {
    $key = $path[$i];
    if (is_array($result) && array_key_exists($key, $result)) {
        if ($i == count($path) - 1) {
            unset($result[$key]); // deleting an element with the last key 
        } else {
            $result = &$result[$key];
        }
    } else {
        break; // not found
    }
}

unset($result); // resetting value by reference

print_r($arr);

fiddle

  •  Tags:  
  • php
  • Related