首页 > 解决方案 > 使用保存的字符串作为对象内容的目标

问题描述

我们正在处理大量 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"
        }]
    }
}]

标签: phpjson

解决方案


变量变量不会像您尝试过的那样处理数组键或箭头运算符。你可以通过使用来做你想做的事情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);

推荐阅读