gutasaputra gutasaputra - 1 year ago 56
PHP Question

how to retrieve multiple array json with php

i know it sounds so easy. just use foreach looping or json_decode, and you can retrieve json data.

yeah it was, until i got multiple array json when trying retrieving data from elasticsearch.

im confused how to retrieve this :

"status": "taken",
"_shards": {
"total": 5,
"successful": 5,
"failed": 0

"hits": {
//goes here

//goes here


"date-created": "2016-06-06"

i use this to retrieve my first data :

$result = json_decode(json_encode($product),true);
echo "total took:";
echo $result['took'];

echo "total shards:";
echo $result['_shards']['total'];

the problem is,i cant retrieve data inside hits.
how can i retrieve hits id : 1234 ?

echo"view all total hits :";
echo $result['hits']['total'];
echo"view all total msg:";
echo $result['hits']['msg'];

echo"view hist data :";
echo json_decode(json_encode($result['hits']['hits']), true);

i got this error :

Message: Array to string conversion

please help me to fix this out.
many thanks in advance.

Answer Source

Try this it's work for me.

    $result= '{"took":3,"status": "taken","_shards": {"total": 5,"successful": 5,"failed": 0},"hits": {"total":2,"msg":"ilusm","hits":[{"id":1234},{"id":4321}]},"date-created": "2016-06-06"}';

    $array= json_decode($result, true);

    echo $array["hits"]["hits"][0]['id']; //output 1234

output : 1234