首页 > 解决方案 > 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

我将不胜感激这里的任何帮助。

标签: phpjson

解决方案


只要$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 的对象,则只会返回第一个找到的对象。


推荐阅读