2017-01-30 12 views
0

手動ループを作成して、開始しているプロジェクトで別のAPIで使用されているjsonを作成しました。下記をご覧ください。JSONを手動で作成するPHPループ

問題は、APIが私のjson出力を認識していないことです。私のループの結果をチェックし、それは正常に見えます。

私の結果(エコー)を直接コピー&ペーストすれば正常に動作しますが、私のループでは動作しません。誰もが何かイデアを持っていますか?

foreach ($array['hits'] as $key => $value) { 

    $message = $message.'{ 
      "title":"'.$value['Title'].'", 
      "image_url":"'.$value['image'].'", 
      "subtitle":"'.substr($value['Detail'],0,120).'", 
      "buttons":[ 
        { 
          "type":"web_url", 
          "url":"'.SITE_ROOT_URL.$value['URL'].'?utm_source=chatbot", 
          "title":"Leia mais" 
        } 
      ] 
    },'; 

} 

$message = '{"messages": [ 
      { 
        "attachment":{ 
          "type":"template", 
          "payload":{ 
            "template_type":"generic", 
            "elements":['.rtrim($message,",").'] 
          } 
        } 
      } 
    ] 
}'; 

echo $message; 

でvar_exportの出力($配列[ 'ヒット'])のようになります。

array (0 => array ('ID' => '69', 'Title' => 'This is an example', 'URL' => 'example/1', 'Detail' => 'Some description here...', 'image' => 'image1.png', 'objectID' => '75877631')), 1 => array .... 
+0

。 –

+3

なぜ 'json_encode()'を使いたくないのですか? – Barmar

+0

@JayBlanchard私はJSONを手作業で作成すると言っているほど遠くには行かないでしょう - それを呼び出すいくつかの本物のケースがありますが、確かにそうではありません。 'json_encode'は[特定の状況で誤った種類の配列を出力する]ことができます(https://eval.in/727141)。 –

答えて

3

手でJSONを生成しません。配列を作成し、json_encode()を使用します。

$messages = array(); 
foreach ($array['hits'] as $key => $value) { 
    $messages[] = array(
     'title' => $value['Title'], 
     'image_url' => $value['image'], 
     'subtitle' => substr($value['Detail'], 0, 120), 
     'buttons' => array(
      array(
       'type' => 'web_url', 
       'url' => SITE_ROOT_URL.$value['URL'].'?utm_source=chatbot', 
       'title' => "Leia mais" 
      ) 
     ) 
    ); 
} 
$result = array(
    'messages' => array(
     'attachment' => array(
      'type' => 'template', 
      'payload' => array(
       'template_type' => 'generic', 
       'elements' => $messages 
      ) 
     ) 
    ) 
); 
echo json_encode($result); 

DEMO

あなたの手で構築JSON配列やオブジェクトの要素をPHP配列に直接マッピングする方法に注意してください。 JSONが含まれている場合:

{ "something": "something else" } 

対応するPHPは次のとおりです。あなたは、手動でそのようなJSONを作成することはありません

array("something" => "something else") 
+0

ありがとう、レッスンは学んだ! :-)なぜ、結果がecho json_encode($ result)で印刷されないのかを理解しようとしています。 – czmarc

+0

それは私のために働く。私はデモを追加しました。 – Barmar

+0

「Title」の代わりに「title」というミスがありました。 – Barmar

関連する問題