2016-12-20 7 views
0

私はGoogleのNatural Language APIを使用していますが、正常に動作し、データを返しています。私はちょうどそれを正しく解析することができません。私はAJAXなどで使用できるJSONオブジェクトを作成したいと思います。私が必要とするのは主に文章とその感情です。 ADDEDPHPで配列を使用したオブジェクトの解析

object(Google\Cloud\NaturalLanguage\Annotation)#21 (1) { 
    ["info":"Google\Cloud\NaturalLanguage\Annotation":private]=> 
    array(3) { 
    ["documentSentiment"]=> 
    array(2) { 
     ["magnitude"]=> 
     float(1.4) 
     ["score"]=> 
     int(0) 
    } 
    ["language"]=> 
    string(2) "en" 
    ["sentences"]=> 
    array(2) { 
     [0]=> 
     array(2) { 
     ["text"]=> 
     array(2) { 
      ["content"]=> 
      string(19) "I love everything!\" 
      ["beginOffset"]=> 
      int(0) 
     } 
     ["sentiment"]=> 
     array(2) { 
      ["magnitude"]=> 
      float(0.8) 
      ["score"]=> 
      float(0.8) 
     } 
     } 
     [1]=> 
     array(2) { 
     ["text"]=> 
     array(2) { 
      ["content"]=> 
      string(18) "I hate everything!" 
      ["beginOffset"]=> 
      int(21) 
     } 
     ["sentiment"]=> 
     array(2) { 
      ["magnitude"]=> 
      float(0.6) 
      ["score"]=> 
      float(-0.6) 
     } 
     } 
    } 
    } 
} 

は私のPHPコードの非常に最後のビットがある:

$annotation = $language->analyzeSentiment($text); 
$sentiment = $annotation->sentiment(); 
echo 'Text: ' . $text . ' 
Sentiment: ' . $sentiment['score'] . ', ' . $sentiment['magnitude']; 
return $sentiment; 

これが成功のためのスコアと大きさを返します。私は、私は戻って取得このオブジェクトに苦労しています配列の一部に表示されているような全体的な "文書" "documentSentiment"。私が必要とするのは(これに加えて)sentencesの下のデータです。特に、content,magnitudeおよびscoreである。 $sentiment['sentences']以来

+0

あなたは、あなたが取得したいものの一例を示すことができます希望のフォーマット。コード構造を構築してそこに到達する方法を調べる方が簡単です。 – Sean

+0

@Seanありがとうございました...私が助けてくれると思われる詳細をいくつか追加しました。 – jonmrich

+0

'json_encode()'と 'json_decode()'を使うと、配列からjsonフィードを作成できます。それがあなたが強くしたいのかどうかはわかりません。 – Nicolas

答えて

2

は配列です -

["sentences"]=> 
    array(2) { 
     ... 
    } 

例えばforeach()であなたは、値をループする必要が - に

.... 
echo 'Text: ' . $text . ' 
Sentiment: ' . $sentiment['score'] . ', ' . $sentiment['magnitude']; 

foreach($sentiment['sentences'] as $sentence){ 
    echo 'Text: ' .$sentence["text"]["content"] . ' 
    Sentiment: ' . $sentence["sentiment"]["score"] . ', ' . $sentence["sentiment"]["magnitude"]; 
} 
関連する問題