php - 使用保存的字符串作为对象内容的目标
问题描述
我们正在处理大量 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"
}]
}
}]
解决方案
变量变量不会像您尝试过的那样处理数组键或箭头运算符。你可以通过使用来做你想做的事情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);
推荐阅读
- javascript - Angular 7 location.back 无需重新加载页面
- python - Python脚本执行和中断
- sql - T-SQL如何将层次结构级别更改为上升而不是下降?
- python - 用引用列表的数据框中的完整单词替换缩写词
- python - 通过 Homebrew 卸载/重新安装 Python 后,我丢失了 Python 包。有没有办法可以恢复我所拥有的清单?
- r - 使用 R 自动化对 Web 搜索表单的多个请求
- docker - 如何在主机网络内 ping Docker-Container?
- reactjs - 反应:useContext 值未在嵌套函数中更新
- docker - 在 Gitlab 构建期间在 Docker 映像中创建文件
- linux - 是否可以通过 Azure TFS 的发布管道在 Linux 机器上运行 vstest