【问题标题】:how to retrieve multiple array json with php如何使用php检索多个数组json
【发布时间】:2016-10-31 16:49:43
【问题描述】:

我知道这听起来很容易。只需使用 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);

我收到了这个错误

消息:数组到字符串的转换

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

【问题讨论】:

  • print_r($result) 并显示您的数组。
  • print_r($result);显示输出
  • $string = '{"took":3,"status": "taken","_shards": {"total": 5,"successful": 5,"failed": 0} ,"点击数": {"总":2,"msg":"ilusm","点击数":[{"id":1234},{"id":4321}]},"日期创建":" 2016-06-06"}'; $arr = json_decode($string, true); var_dump($arr["hits"]["hits"][0]["id"]);

标签: php arrays json elasticsearch libraries


【解决方案1】:

试试这个它对我有用。

    $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

【讨论】:

    【解决方案2】:
    $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"]);
     }
    
    }
    

    【讨论】:

      【解决方案3】:

      我觉得你对 json & php 数据管理有点困惑。

      你能告诉我们 $product 变量是什么吗? (字符串,对象/数组)。

      通常你将 json 数据作为字符串获取并使用 json_decode 将其解析为 php 变量。

      $product 的类 Javascript 对象声明是无用的。

      【讨论】:

        猜你喜欢
        • 2013-12-25
        • 2016-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多