JSON:使用php从数组中提取特定行

我正在尝试从我拥有的JSON格式中获取特定数据。我在练习中使用预构建的json。


JSON格式是这样的:


[

{

"userId": 1,

"id": 1,

"title": "sunt aut facere repellat provident occaecati excepturi optio 

 reprehenderit",

"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et 

cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt   

rem eveniet architecto"

},

{

"userId": 1,

"id": 2,

"title": "qui est esse",

"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor 

beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil 

molestiae 

ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"

},

{

"userId": 1,

"id": 3,

"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",

"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut 

ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius 

odio et labore et velit aut"

}

等等...


所以我要做的是从每个对象中获取标题数组。


这是我的代码:


<?php

$url = "https://jsonplaceholder.typicode.com/posts" ;

//  Initiate curl

$ch = curl_init() ;

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

$result = curl_exec($ch) ;

curl_close($ch) ;


$data = json_decode($result);


foreach ($data as $datavalue) {

echo $datavalue->title;

echo "<br/>" ;

}

现在,我要显示的是特定对象的标题,比如说user id = 2。


我该如何说服。请帮助我的查询。任何帮助,我们真的很感激。


白衣染霜花
浏览 216回答 3
3回答

拉丁的传说

您可以在循环中添加条件以检查想要的行,当找到时,可以将其存储在这样的变量中:<?php&nbsp; $data = json_decode($result);&nbsp; $data = json_decode($result);&nbsp; $userId = 1;&nbsp; $result = null;&nbsp; foreach ($data as $datavalue) {&nbsp; &nbsp; echo $datavalue->title;&nbsp; &nbsp; if ($datavalue->userId == $userId) {&nbsp; &nbsp; &nbsp; &nbsp;$result = $datavalue;&nbsp; &nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp; }&nbsp; &nbsp; echo "<br/>" ;&nbsp; }var_dump($result); // if you want to display the title you can simply do $result->title but remember to check if $result is not null

缥缈止盈

您可以使用以下内容:$id = 2;getTitle($data, $id);function getTitle($data = null, $id = null){&nbsp; &nbsp; foreach ($data as $datavalue) {&nbsp; &nbsp; &nbsp; &nbsp; if ($datavalue->id == $id) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo $datavalue->title;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo "<br/>";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP