简体   繁体   中英

read json object in php

I have some json object like this:

{"g_aaa77":
    {"'title'":"title2",
        "'r_a6cff'":                
            {"name":"name2","price":"2"},
        "'r_7fc7b'":   
            {"name":"name22","price":"22"}
     },
 "g_a36b5":
     {"title":"title1",
         "r_4e122": 
             {"name":"name1","price":"1"},
         "r_155fa":
             {"name":"name11","price":"11"}
     }
}

g_aaa77 and g_a36b5 are a random string.

Also r_a6cff , r_7fc7b , r_4e122 , r_155fa

How can I read this json?

Normally is this way:

$json = { .. };

$json->g_a36b5->title;

But I do not have 'g_a36b5'. it is a random string.

maybe I must convert this json to another or something like this.

can u please tell me how can I read this json?

First of, json_decode your json.

$array = json_decode($json, true);

Now you'll need to loop through with a foreach, since you still don't know what the keys are:

foreach($array AS $key => $subarray) {
    echo $key . ": " . print_r($subarray, true);
}

If you don't care about keeping the keys, you can just remove those random strings with array_values .

$array = array_values($array);

Now you can still loop through it, or just address an array element directly via numeric key:

print_r($array[0]);
echo $array[1]['title']; // title1

Example: https://3v4l.org/s2it1

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