2

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?

2
  • Start by json_decoding it Commented Jun 12, 2016 at 23:53
  • You can use json_decode() then a foreach loop Commented Jun 12, 2016 at 23:54

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.