使用保存的字符串作为对象内容的目标

时间:2019-07-08 13:02:35

标签: php json

我们正在处理大量json数据,并试图通过字符串变量定义要使用的部分。

所以我正在尝试将字符串转换为对象内容的对象路径。

这有效...

<?php 
$pmdd_ds_json_obj = json_decode($pmdd_ds_json_data);
echo $pmdd_ds_json_obj[0]->title->rendered; 
// shows "Wisconsin Investment Board"
?>

但是我似乎无法像上面那样加载它。

$num = 0;
$root =  "pmdd_ds_json_obj[$num]->";
$content = "title->rendered"
$obj_content = ${$root.$content};

// tried other approached too.
echo $root.$content;
echo ${$root.$content};
echo ${"$root.$content"};

我在做什么甚至可能吗?尝试了很多变化,需要一双崭新的眼睛!

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"
        }]
    }
}]

1 个答案:

答案 0 :(得分:1)

变量变量不会像您尝试的那样处理数组键或箭头运算符。您可以使用eval()做您想做的事情,但不要:P

但是,json_decode接受一个标志以返回关联数组而不是stdClass对象。 https://www.php.net/manual/en/function.json-decode.php

$foo = json_decode($json, true);

一旦有了,就可以通过使用函数将点存储为变量来解析数组值,从而获得所需的值。查看此答案: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

resolve()函数的其他更改以使其也可以接受对象:

$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);