简体   繁体   中英

How to access array list in Json by php?

I am currently working with Accessing json using php in wordpress. I have successfully decoded the json but when i try to access the values it doesn't fetch. I am trying to access the Cluster_ID and Image values. Here's my api link http://ec2-13-127-149-66.ap-south-1.compute.amazonaws.com:5000/api/news 在此处输入图像描述

I have tried the following code:

<?php

/**

 *Plugin Name: plugin two
 
 **/
function myjson8(){
    $request = wp_remote_get( 'http://ec2-13-127-149-66.ap-south-1.compute.amazonaws.com:5000/api/news' );

if( is_wp_error( $request ) ) {
    return false; // Bail early
}

$body = wp_remote_retrieve_body( $request );

$data = json_decode( $body );

if( ! empty( $data) ) {
    foreach( $data  as $product ) {
        echo $product->Cluster_ID;
        foreach($data->data as $news){
            echo $news->Image;
        }
}
    }
}

Taking the data from the news feed that you supplied then placing it in a JSON viewer you get:

基础结构

On opening level 0 we get

0级

This is not what you want so we need to look at level 1 and its structure

一级结构

So your code would be:

for($x=0; $x<count($data[1]); $x++ ) {
  $clusterId = $data[1][$x]['Cluster_ID'];
  for( $p=0; $p<count( $data[1][$x]['data'] ); $p++ ) {
    $pic =  $data[1][$x]['data'][$p];
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM