如何使用 php 检索多个数组 json

how to retrieve multiple array json with php

我知道这听起来很简单。只需使用 foreach 循环或 json_decode,您就可以检索 json 数据。

是的,直到我尝试从 elasticsearch 检索数据时得到多个数组 json。

我对如何检索这个感到困惑:

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

  "hits": {
        "total":2,
        "msg":"ilusm",
        "hits":
                    [
                      {
                        //goes here
                        "id":1234
                      },

                      {
                        //goes here
                        "id":4321
                      }

                    ]

         },
  "date-created": "2016-06-06"
}

我用它来检索我的第一个数据:

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

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

问题是,我无法检索命中中的数据。 我如何检索命中 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);

我得到这个错误

Message: Array to string conversion

请帮我解决这个问题。 非常感谢。

试试这个对我有用。

    $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

输出 : 1234

$string = '{"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"}'; 

$hits= json_decode($string, true); 
$hits = $hits['hits']['hits'];
foreach($hits as $hitsIndex => $hitsValue){

 if($hitsValue["id"] == '1234'){
  var_dump($hitsValue["id"]);
 }

}

我认为您对 json 和 php 数据管理有些困惑。

你能告诉我们 $product 变量是什么吗? (字符串,object/array)。

通常你会得到 json 字符串形式的数据,然后使用 json_decode.

将其解析为 php 个变量

您对 $product 的 Javascript 类对象声明没有用。