2014-03-27 147 views
1

在以JSON形式執行彈性搜索和存儲結果獲取特定元素從JSON在PHP

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 

如何得到它?

+1

嘗試將您的JSON轉換爲關聯數組傳遞真正的第二個參數'json_decode($ yourjson,真)'。 – fian

+0

問題不在於getter,而在於'$ i'不是一個對象(看它是如何是119,然後是空的,然後是* stdClass。 – h2ooooooo

+0

@fian - 已經做到了 –

回答

2

您可以使用以下;

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

試試這個

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

    }