php - JSON:按 ID 获取项目
问题描述
我有一个这样的JSON:
[
{
"_ID": "3",
"dash_title": "some title",
"dash_description": "some description"
},
{
"_ID": "2",
"dash_title": "some title",
"dash_description": "some description"
},
{
"_ID": "1",
"dash_title": "some title",
"dash_description": "some description"
}
]
我需要获取所有对象并仅显示底部的第一个和第三个。现在我只需使用对象的序号就可以做到这一点,如下所示:
function _dashboard_clients_info() {
$url = 'some JSON URL';
$request = wp_remote_get( esc_url_raw( $url ) );
$html = wp_remote_retrieve_body( $request );
$data = json_decode( $html );
$head = $data[2];
$foot = $data[0];
if( ! empty( $head->dash_description ) ) {
echo wpautop( '<div class="dash_head">' . $head->dash_description . '</div>' );
echo $head->html_css_js;
} else { };
if( ! empty( $foot->dash_description ) ) {
echo wpautop( '<div class="dash_foot">' . $foot->dash_description . '</div>' );
echo $foot->html_css_js;
} else { };
}
问题是如果一个对象被添加到 JSON 中,那么从底部开始的第一个对象的序列号也会改变。但对象 ID 保持不变。
我想遍历这个 JSON 中的所有 ID 并传入$head
id=1
, $foot
id=3
。
我将不胜感激这里的任何帮助。
解决方案
只要$data
是对象数组且每个对象 id 都是唯一的,您就可以使用该array_filter
函数搜索具有特定 id 的条目。
$head = current(array_filter($data, function($current) {
return $current->_ID == 1;
}));
$foot = current(array_filter($data, function($current) {
return $current->_ID == 3;
}));
注意:如果数组包含多个具有相同 id 的对象,则只会返回第一个找到的对象。
推荐阅读
- python - 如何使用 rpy2 api 从 python 脚本中正确获取 R sessionInfo()?
- kotlin - Android-Things:将 gpiocallback 函数迁移到暂停协程函数
- c# - 如何在用户的声明列表中保留多个 ClaimTypes.Role 值?
- google-sheets - 查询功能按问题排序 Google 表格
- apache-beam - 如何在 Apache Beam 中生成序列号?
- c# - C# - 更改从串行端口接收的数据格式
- apache-spark-sql - 在 PySpark 中读取 DataFrames、.csv 文件时。我收到此错误“未定义名称'spark'”
- go - golang复制功能理解
- postgresql - 如何在 postgres 中为数字类型自动使用适当的精度/比例?
- ruby-on-rails - Centos 7:确保 `gem install pg -v '0.18.4' --source