【问题标题】:PHP parsing of a multi-dimensional array from Elastic Search来自 Elastic Search 的多维数组的 PHP 解析
【发布时间】:2019-06-16 03:27:03
【问题描述】:

我有一个名为$response 的多维数组(我只得到一个结果,但实际上有很多..)

Array
(
    [took] => 17
    [timed_out] => 
    [_shards] => Array
        (
            [total] => 5
            [successful] => 5
            [skipped] => 0
            [failed] => 0
        )

    [hits] => Array
        (
            [total] => 16
            [max_score] => 13.034995
            [hits] => Array
                (
                    [0] => Array
                        (
                            [_index] => zh3
                            [_type] => zone_humide
                            [_id] => 4950467
                            [_score] => 13.034995
                            [_source] => Array
                                (
                                    [surfcal_ha] => 2.26
                                    [@timestamp] => 2019-01-21T19:25:48.826Z
                                    [@version] => 1
                                    [donnee_id] => 3355
                                    [zhu_cbi] => 82
                                    [zh_nom] => Coupigny
                                    [gid] => 4950467
                                    [zh_part_id] => 079FONTEN0011
                                    [is_pe] => 
                                )

                        )
                )

        )

)       

我想获得 gid 属性。为此,我尝试了:

foreach ($response['hits']['hits'][0]['_source'] as $result) {
echo $result['gid'];
}

但我收到了 PHP 警告:

PHP 警告:非法字符串偏移 'gid'

我尝试了不同的方法.. 添加另一个 foreach 循环,更改回显但没有任何效果。我尝试了来自 StackOverflow 的 that,但也没有结果。好吧,我想我真的被困住了。

对这个问题有什么想法吗?
任何帮助将不胜感激! 谢谢

【问题讨论】:

  • 我已经为你添加了答案。有帮助吗?

标签: php arrays elasticsearch


【解决方案1】:

$response 数组只有一个父元素。为什么用foreach

试试吧

echo $response['hits']['hits'][0]['_source']['gid'];

【讨论】:

    【解决方案2】:

    这是因为你在$response['hits']['hits'][0]['_source']上使用了foreach
    例如。 1.在foreach的第一个循环中会得到$result['surfcal_ha']
    2. 在第二个循环中它得到$result[@timestamp]
    所以直到它没有得到$result['gid'] 它会打印警告。尝试在下面不使用foreach

    echo $response['hits']['hits'][0]['_source']['gid'];
    

    【讨论】:

      猜你喜欢
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      相关资源
      最近更新 更多