首页 > 解决方案 > 我可以通过 Id 获取特定的 JSON 值吗?

问题描述

我想从下面的 JSON中得到typeId: 11的相应日期。typeId 的顺序总是不同的,所以它并不总是有效,例如,总是处理第二个值。

    {
    "page": 1,
    "totalsCount": 1,
    "isLastPage": true,
    "lastPageNumber": 1,
    "firstOnPage": 1,
    "lastOnPage": 1,
    "itemsPerPage": 50,
    "entries": [
        {
            "id": 60132,
            "statusName": "GIT",
            "dates": [
                {
                    "orderId": 60132,
                    "typeId": 7,
                    "date": "2021-06-03T00:00:00+02:00"
                },
                {
                    "orderId": 60132,
                    "typeId": 11,
                    "date": "2021-05-28T00:00:00+02:00"
                },
                {
                    "orderId": 60132,
                    "typeId": 16,
                    "date": "2021-05-27T20:20:28+02:00"
                },
                {
                    "orderId": 60132,
                    "typeId": 2,
                    "date": "2021-05-27T20:19:21+02:00"
                },
                {
                    "orderId": 60132,
                    "typeId": 4,
                    "date": "2021-06-03T15:16:14+02:00"
                }
            ]
        }
    ]
}

到目前为止,我的方法没有得到任何结果:

$json = file_get_contents($orders);
$arr = json_decode($orders);
foreach($arr->entries as $order => $value) {

echo '<th scope="row">' . $value->dates->[typeId='11'].date . '</th>';
}

我的错误在哪里?

标签: phpjson

解决方案


对于这种情况,我通常会写一个这样的简单函数:

function getDate(array $dates, $typeId) {
    foreach ($dates as $date) {
        if ($date['typeId'] === $typeId) {
            return $date;
        }
    }
    return null;
}

推荐阅读