2016-10-07 24 views
0

我正在玩twitter API,我試圖解析json輸出。但不知何故,我做錯了什麼,我沒有得到我想要的。從解析的JSON輸出中獲取對象時遇到問題

在這種情況下,我用PHP編寫。開始循環通過數組和screen_name和文本正在相應地工作。

foreach ($statuses as $obj) { 

    $screen_name = filter_var($obj->user->screen_name, FILTER_SANITIZE_STRING); 
    $text   = filter_var($obj->text, FILTER_SANITIZE_STRING); 
    $urls   = filter_var($obj->entities->urls->url, FILTER_SANITIZE_URL); 
} 

的JSON陣列輸出:

array (
    0 => 
    stdClass::__set_state(array(
    'created_at' => 'Fri Oct 07 15:31:01 +0000 2016', 
    'text' => 'test', 
    'entities' => 
    stdClass::__set_state(array(
     'hashtags' => 
     array (
     0 => 
     stdClass::__set_state(array(
      'text' => '30Under30', 
      'indices' => 
      array (
      0 => 36, 
      1 => 46, 
     ), 
     )), 
    ), 
     'symbols' => 
     array (
    ), 
     'user_mentions' => 
     array (
    ), 
     'urls' => 
     array (
     0 => 
     stdClass::__set_state(array(
      'url' => 'https://Forbes.com', 
      'expanded_url' => 'https://twitter.com/i/web/status/784415744427687936', 
      'display_url' => 'twitter.com/i/web/status/7…', 
      'indices' => 
      array (
      0 => 117, 
      1 => 140, 
     ), 
     )), 
    ), 
    )), 
    'source' => 'Sprinklr', 
    'in_reply_to_screen_name' => NULL, 
    'user' => 
    stdClass::__set_state(array(
     'id' => 91478624, 
     'screen_name' => 'test', 
     'url' => 'http://Forbes.com', 
     'entities' => 
     stdClass::__set_state(array(
     'url' => 
     stdClass::__set_state(array(
      'urls' => 
      array (
      0 => 
      stdClass::__set_state(array(
       'url' => 'http://Forbes.com', 
       'expanded_url' => 'http://forbes.com', 
       'display_url' => 'forbes.com', 
       'indices' => 
       array (
       0 => 0, 
       1 => 22, 
      ), 
      )), 
     ), 
     )), 
     'description' => 
     stdClass::__set_state(array(
      'urls' => 
      array (
      0 => 
      stdClass::__set_state(array(
       'url' => 'http://Forbes.com', 
       'expanded_url' => 'http://Forbes.com', 
       'display_url' => 'Forbes.com', 
       'indices' => 
       array (
       0 => 28, 
       1 => 48, 
      ), 
      )), 
     ), 
     )), 
    )), 
     'protected' => false, 
     'notifications' => false, 
    )), 
    'geo' => NULL, 
    'lang' => 'en', 
)), 
) 
+0

將很高興有一個你想要的結果的例子。我的猜測只是傳遞第二個參數爲真json_decode($ string,true)'。 http://php.net/manual/en/function.json-decode.php –

+0

我想要第一個''url'=>'https:// Forbes.com','參數。我認爲它圍繞第32行。對我來說,它看起來像路徑是entities-> urls-> url。然而這是行不通的 – RvdM

+0

'urls'是一個數組,所以你需要'$ obj-> entities-> url [0] - > url' – Barmar

回答

0

由於urls是一個數組,你需要建立索引。

$urls   = filter_var($obj->entities->urls[0]->url, FILTER_SANITIZE_URL);