【问题标题】:How to filter JSON in php?如何在php中过滤JSON?
【发布时间】:2019-05-03 11:05:47
【问题描述】:

我有这个 JSON

[
{"name":"Juan","Sex":"Male","ID":"1100"},{"name":"Maria";"Sex":"Female","ID":"2513"},{"name":"Pedro";"Sex":"Male","ID":"2211"}
]

我只想获取 ID 为 2513 的人

[
{"name":"Maria";"Sex":"Female","ID":"2513"}
]

【问题讨论】:

标签: php json filter


【解决方案1】:

使用json_decode() 将 JSONString 转换为 PHP 对象数组

$str = '[{"name":"Juan","Sex":"Male","ID":"1100"},"name":"Maria";"Sex":"Female","ID":"2513"},{"name":"Pedro";"Sex":"Male","ID":"2211"}]';

$arr = json_decode($str);

foreach ( $arr as $obj ){
    if ( $obj->ID == 2513 ) {
        echo $obj->name;
    }
}

【讨论】:

    【解决方案2】:

    您的 JSON 字符串无效。首先用逗号, 替换所有分号;,然后尝试使用array_filter() 或任何其他方式,例如foreach()if 条件等。我使用了array_filter() 方式,希望它有所帮助:)

    <?php
    $json = '[{"name":"Juan","Sex":"Male","ID":"1100"},{"name":"Maria","Sex":"Female","ID":"2513"},{"name":"Pedro","Sex":"Male","ID":"2211"}]';
    $array = json_decode($json,1);
    $ID = 2513;
    $expected = array_filter($array, function ($var) use ($ID) {
        return ($var['ID'] == $ID);
    });
    print_r($expected);
    ?>
    

    演示: https://3v4l.org/kZrMo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 2016-05-24
      • 1970-01-01
      • 2021-12-23
      相关资源
      最近更新 更多