在PHP中从JSON获取特定元素

时间:2014-03-27 07:05:32

标签: php arrays json

执行弹性搜索并以JSON格式存储结果

stdClass Object (
    [took] => 119
    [timed_out] => 
    [_shards] => stdClass Object (
        [total] => 5 
        [successful] => 5 
        [failed] => 0 
    )
    [hits] => stdClass Object (
        [total] => 3 
        [max_score] => 1 
        [hits] => Array ( 
            [0] => stdClass Object (
                [_index] => movies 
                [_type] => movie 
                [_id] => 3 
                [_score] => 1 
                [_source] => stdClass Object (
                    [title] => The MATRIX 
                    [year] => 1975
                )
            )
            [1] => stdClass Object (
                [_index] => movies
                [_type] => movie
                [_id] => 8
                [_score] => 1
                [_source] => stdClass Object (
                    [title] => The MATRIX
                    [year] => 1975
                )
            )
            [2] => stdClass Object (
                [_index] => movies
                [_type] => movie
                [_id] => 4
                [_score] => 1
                [_source] => stdClass Object (
                    [title] => The MATRIX
                    [year] => 1975
                )
            )
        )
    )
) 

我希望在上面的每部电影和年份中获得价值 我试过了

foreach($result as $i)
{
    echo $i->title;
    echo $i->year;
}


Notice: Trying to get property of non-object in D:\xampp\htdocs\esearch\index.php on line 16

Notice: Trying to get property of non-object in D:\xampp\htdocs\esearch\index.php on line 17

如何获得它?

2 个答案:

答案 0 :(得分:2)

您可以使用以下内容;

foreach($result->hits->hits as $movie)
{
    echo $movie->_source->title;
    echo $movie->_source->year;
}

答案 1 :(得分:1)

试试这个

    foreach($result->hits->hits as $i)
    {
        echo $i->_source->title;
        echo $i->_source->year;

    }