Variable variables won't process the array key, or arrow operators, like you've tried. You could do what you're trying to do by using eval(), but don't :P
However, json_decode accepts a flag to return an associative array rather than stdClass objects. https://www.php.net/manual/en/function.json-decode.php
$foo = json_decode($json, true);
Once you have that, you could get the value you want by using a function to resolve an array value by dot notation, which can be stored as a variable. See this answer: https://stackoverflow.com/a/14706302/2286736
<?php
$json = '[{
"date": "2019-07-04T10:21:15",
"title": {
"rendered": "Wisconsin Investment Board"
}
}]';
// decode as associative array
$pmdd_ds_json_obj = json_decode($json, true);
/**
* @link https://stackoverflow.com/a/14706302/2286736
*/
function resolve(array $a, $path, $default = null) {
$current = $a;
$p = strtok($path, '.');
while ($p !== false) {
if (!isset($current[$p])) {
return $default;
}
$current = $current[$p];
$p = strtok('.');
}
return $current;
}
// key variable
$key = '0.title.rendered';
// value can be resolved by the dot notation path
$value = resolve($pmdd_ds_json_obj, $key);
var_dump($value); // Wisconsin Investment Board
Additional changes to the resolve() function to allow it to accept objects as well:
$json = '[{
"date": "2019-07-04T10:21:15",
"title": {
"rendered": "Wisconsin Investment Board"
},
"_links": {
"self": [{
"href": "https:\/\/refi.global\/europe\/wp-json\/wp\/v2\/posts\/309891"
}]
}
}]';
// decode as normal (with stdClass)
$pmdd_ds_json_obj = json_decode($json);
function resolve($a, $path, $default = null) {
$current = $a;
$p = strtok($path, '.');
while ($p !== false) {
if (
(is_array($current) && !isset($current[$p]))
|| (is_object($current) && !isset($current->$p))
) {
return $default;
}
$current = is_array($current) ? $current[$p] : $current->$p;
$p = strtok('.');
}
return $current;
}
// key variable
$key = '0._links.self.0.href';
// value can be resolved by the dot notation path
$value = resolve($pmdd_ds_json_obj, $key);