使用多个对象进行Php json解码
Json 如何按id搜索姓名?使用多个对象进行Php json解码,php,html,json,api,decode,Php,Html,Json,Api,Decode,Json 如何按id搜索姓名? 如果我只想选择Josh,我该怎么办 现在我用php和foreach循环解码json $url = "articles.json"; $json = json_decode(file_get_contents($url)); foreach($json->articles as $articles){ echo $articles->name; } 我只想选择id为1的名称 $json = '{ "articles": [
如果我只想选择Josh,我该怎么办 现在我用php和foreach循环解码json
$url = "articles.json";
$json = json_decode(file_get_contents($url));
foreach($json->articles as $articles){
echo $articles->name;
}
我只想选择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对象([id]=>1[name]=>Josh)
这样,您就可以将id
和name
绑定在一起
正常访问,如: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";
}
}
作为fieldValue
(id
或name
)的一个小函数,使用url
,checkValue
作为附加参数更好
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;
}
}
}
根据注释+示例,可以编写上述内容
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") ;
,这很简单:
function findById($articles, $id){
foreach($articles as $article){
if($article['id'] === $id)
return $article;
}
}
在这个答案中,您需要将true
作为json\u decode()
的第二个参数传递,以便将数据转换为关联数组
$json = json_decode(file_get_contents($url), true);
您可以使用array\u 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
那不行(功能部分)。。。当你调用这个函数时,已经没有了$articles->id
..@FirstOne你是对的,我到底在写什么:)onemoment@FirstOne已删除,请相应编辑答案,谢谢。:)你必须做一个forloop。如果你想搜索一种查询,你需要使用一个像jql、jsonpath这样的框架,或者一个更大的内部有json查询的框架。一个附带说明,你调用它也可以作为对象使用(在json_解码中没有true
),方法是将$article['id']
更改为$article->id
@FirstOne year我知道,但是我发现另一个更容易阅读,我不喜欢那一个不知道为什么
echo $results[0]->name; // echo the name of the first match