的Json
{
"articles": [
{
"id": 1,
"name": "Josh"
},
{
"id": 2,
"name": "Jenny"
},
{
"id": 3,
"name": "Chris"
}
]
}
如何按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的名称。
答案 0 :(得分:3)
Public Class TaskHelper
Public Shared Function RunAllSequential(ByVal Tasks() As Task) As Task
For i = 0 To Tasks.Length - 2 'Using -2 since the last task don't need to start another one.
Dim j As Integer = i
Tasks(i).ContinueWith(Sub() Tasks(j + 1).Start())
Next
Tasks(0).Start() 'Start the first task.
Return Task.WhenAll(Tasks)
End Sub
End Class
输出:
stdClass对象([id] => 1 [name] => Josh)
这样,您就可以Await TaskHelper.RunAllSequential(tasklist.ToArray())
和$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);
绑定。
正常访问它,如下所示:id
答案 1 :(得分:2)
您可以使用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
答案 2 :(得分:1)
$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;
}
}
}
基于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") ;
答案 3 :(得分:1)
这很简单:
setDetailsFragment()
在这个答案中,您需要将function findById($articles, $id){
foreach($articles as $article){
if($article['id'] === $id)
return $article;
}
}
作为true
的第二个参数传递,以便将数据转换为关联数组。
json_decode()