[英]How do i retrieve api data using foreach loop in php
This is my data and i want to print the value using decode Json data into array value so please help me out.这是我的数据,我想使用将 Json 数据解码为数组值来打印值,所以请帮帮我。
{
"total_results": 10000,
"page": 1,
"per_page": 15,
"photos": [
{
"id": 1687093,
"width": 3079,
"height": 4619,
"url": "https://fingerprintdesigns.studio/",
"photographer": "Cameron Casey",
"photographer_id": 455136,
"src": {
"original": "https://fingerprintdesigns.studio/",
},
"liked": false
} ] }
I want to retrieve total_results
and photos->src->original
so how can i do?我想检索total_results
和photos->src->original
我该怎么办?
First you'll need to use json_decode to converts it into a PHP object:首先,您需要使用json_decode将其转换为 PHP object:
$response = json_decode($url);
To retrieve total_results :要检索total_results :
echo $response->total_results;
You'll have to loop through photos attribute since it's an array of objects:您必须遍历照片属性,因为它是一组对象:
foreach ($response->photos as $photo) {
echo $photo->src->original;
}
If you have only one object of photos then you can do as below如果您只有一张 object 的照片,那么您可以执行以下操作
$obj = '{
"total_results": 10000,
"page": 1,
"per_page": 15,
"photos": [
{
"id": 1687093,
"width": 3079,
"height": 4619,
"url": "https://fingerprintdesigns.studio/",
"photographer": "Cameron Casey",
"photographer_id": 455136,
"src": {
"original": "https://fingerprintdesigns.studio/"
},
"liked": false
} ] }';
// Convert JSON string to Array
$objectArray = json_decode( $obj, true );
print_r($objectArray); // Dump all data of the Array
echo $total_results = $objectArray['total_results']; // Access Array data
echo $originalPhoto = $objectArray['photos'][0]['src']['original'];
// For multiple value
if( is_array( $objectArray['photos'] ) && !empty( $objectArray['photos'] ) ){
foreach ($objectArray['photos'] as $photo) {
echo $photo['src']['original'];
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.