0

I have an multidimensional associative array as follows

$data = Array
(
    [store_name] => Jota
    [social] => Array
        (
            [fb] => 78
            [youtube] => 34
            [twitter] => 97
            [linkedin] => 23
            [pinterest] => 12
            [instagram] => 93
            [flickr] => 45
        )
)

Input to my program is a string that is compose of keys from the above array separated by brackets. E.g

$input = "data[social][fb]"

Question 1 How can I traverse the above array as per the input string pattern & access the value of $data["social"]["fb"]?

Question 2

How can I update the value in the above array followed by a string pattern?

$pattern = "data[social][fb];
$value = "foo";
update_array( $data,  $pattern, $value);
SkyRar
  • 1,107
  • 1
  • 20
  • 37
  • 1
    Why use that type of string `data[social][fb]`??? Use something easier to work with. – AbraCadaver Sep 08 '21 at 20:57
  • I have a beginning for you: `explode('[', str_replace(']', '', "data[social][fb]")); // ["data", "social", "fb"]` but then you gotta loop over the elements to drill down. (Probably can do this more elegantly with Regex, I'm sure someone will suggest) – Phil Tune Sep 08 '21 at 21:01
  • I also asked this same question over 5 years ago and got a good script: https://stackoverflow.com/questions/36334635/dynamically-accessing-multidimensional-array-value – Phil Tune Sep 08 '21 at 21:06
  • @PhilTune But you are using an actual array not a string that sorta looks like an array. – AbraCadaver Sep 08 '21 at 21:11
  • There's no reason to do it this way, but if you quote the keys in the string then https://3v4l.org/nHlAm – AbraCadaver Sep 08 '21 at 21:15

1 Answers1

2

You can extract the keys with a regular expression and then iteratively dig into the data structure:

function getDeep($data, $str) {
    preg_match_all("#\[(.*?)\]#", $str, $keys, PREG_PATTERN_ORDER);
    foreach ($keys[1] as $key) $data = $data[$key];
    return $data;
}

Run like this:

$data = [
    "store_name" => "Jota",
    "social" => [
            "fb" => 78,
            "youtube" => 34,
            "twitter" => 97,
            "linkedin" => 23,
            "pinterest" => 12,
            "instagram" => 93,
            "flickr" => 45,
    ]
];

$input = "data[social][fb]";
echo getDeep($data, $input);
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Thank you! I have updated my post with a Q2. You may have a look please. – SkyRar Sep 10 '21 at 13:17
  • I see the Q2, but a Stack Overflow question should be one question only. Also, as you have seen this answer, this should give you ideas to solve it yourself. Please have a go at it, and if you cannot make it work, then ask a completely new question about it, including your attempt, and the problem with it. – trincot Sep 10 '21 at 13:36