0

This works fine. But how can I ref ['toppings'][2]['type'] by passing it as a string? i.e. $cake = '['toppings'][2]['type']'; echo $yummy + $cake;

<?php
    $json = '
    {
        "type": "donut",
        "name": "Cake",
        "toppings": [
            { "id": "5002", "type": "Glazed" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5004", "type": "Maple" }
        ]
    }';

    $yummy = json_decode($json, true);

    echo $yummy['toppings'][2]['type']; //Maple
?>

Thanks

  • 1
    It’s very hard to tell what you’re asking. What do you mean by “passing it as a string”? What are you expecting your echo to output? Apart from the fact that `+` is not used for concatenation in PHP (you use `.` for that), echoing `$yummy` is just echoing an array, which will throw an error since an array is not a string. So what exactly do you want to do? – Janus Bahs Jacquet Jan 05 '22 at 23:44
  • Sorry for not being clear. As you can see I know how to ref an array. However, I want to construct a string that contains the refs ([‘toppings’][2][‘type’]). The output will still be Maple. – TheKingdom Jan 06 '22 at 13:42
  • I’m still not sure what you’re after. You want to construct a _string_ (that is, a sequence of text characters meant for outputting) which is `['toppings'][2]['type']`? And then what? Later on reinterpret that string as an array ‘path’? So you can echo `$yummy . $string` and that should ‘expand’ to `$yummy['toppings'][2]['type']`? If that’s what you mean, I don’t think it’s possible; you can use string variables for individual parts (`$yummy[$element][$id][$type]`), but not for the whole thing. It also sounds like a very, very bad idea – why would you want to do it to begin with? – Janus Bahs Jacquet Jan 06 '22 at 13:52
  • So I have the answer. – TheKingdom Jan 06 '22 at 19:27
  • https://stackoverflow.com/questions/27929875/how-to-access-and-manipulate-multi-dimensional-array-by-key-names-path This is how it is done - eval("\$result = \$arr{$searchval};"); - very useful when dealing with a complex JSON structure. – TheKingdom Jan 06 '22 at 19:30
  • Like I said, that sounds like a very, very bad idea. There’s a reason the adage goes that _`eval()` is evil_. – Janus Bahs Jacquet Jan 06 '22 at 19:34
  • Sure, eval is a bit of a risk, but I guess we both learned something today ;) – TheKingdom Jan 06 '22 at 20:26

0 Answers0