Php json 多对象解码

Php json decoding with multiple objects

Json

{
    "articles": [
        {
            "id": 1,
            "name": "Josh" 
        },
        {
            "id": 2,
            "name": "Jenny"
        },
        {
            "id": 3,
            "name": "Chris"
        }
    ]
}

如何按 ID 搜索姓名?
如果我只想要 select Josh,我该怎么办?

现在我正在使用 php 和 foreach 循环解码 json。

$url = "articles.json";
$json = json_decode(file_get_contents($url));
foreach($json->articles as $articles){
    echo $articles->name;
}

我只想要 select id 为 1 的名称。

$json = '{
    "articles": [
        {
            "id": 1,
            "name": "Josh" 
        },
        {
            "id": 2,
            "name": "Jenny"
        },
        {
            "id": 3,
            "name": "Chris"
        }
    ]
}';

$json = json_decode($json);
$id = '1';
$result = 'NOT FOUND';
foreach($json->articles as $articles){
    if($articles->id == $id){
        $result = $articles;
    }
}

print_r($result);

输出:

stdClass Object ( [id] => 1 [name] => Josh )

这样你就可以保持 idname 并列。

正常访问,像这样:echo $result->name;

    $url = "articles.json";
    $json = json_decode(file_get_contents($url));
    foreach($json->articles as $articles){
        if($articles->id==1){
           echo "found id equal to 1";
    }
        if($articles->name=="Josh"){
           echo "found Josh";
    }
    }

作为 fieldValueidname)的小函数更好,urlcheckValue 作为附加参数

   Function loopThruJSON ($json,$fieldValue,$checkValue) {
        $json = json_decode($json);
        foreach($json->articles as $articles){
            if($articles->{$fieldValue}==$checkValue){
               return "found ".$fieldValue." equal to ".$checkValue;
            } else {
               return false;
            }
        }
    }

根据FirstOne's评论+例子上面可以写

    Function loopThruJSON ($json,$fieldValue,$checkValue) {
            $json = json_decode($json);
            foreach($json->articles as $articles){
                if($articles->$fieldValue==$checkValue){
                   return "found ".$fieldValue." equal to ".$checkValue;
                } else {
                   return false;
                }
            }
     }
// Usage
echo loopThruJSONID ("articles.json",'id',1) ;
echo loopThruJSONName ("articles.json",'name',"Josh") ;

PHP sandbox example, 3v4l example

这很简单:

function findById($articles, $id){
    foreach($articles as $article){
        if($article['id'] === $id)
           return $article;
    }
}

在这个答案中,您需要将 true 作为 json_decode() 的第二个参数传递,以便将数据转换为关联数组。

$json = json_decode(file_get_contents($url), true);

您可以使用 array_filter 来获取数组中的每一项您想要的 ID。

$id = 1;  // define your id

// filter for that id
$results = array_filter($json->articles, function($x) use ($id) {
    return $x->id == $id;
});

结果将是一个包含零个或多个元素的数组,具体取决于找到 id 的次数。我不确定你需要对结果做什么,但你可以用 foreach 遍历它们,或者像这样按键访问特定元素:

echo $results[0]->name;   // echo the name of the first match