PHP循环手动创建JSON

时间:2017-01-30 22:02:29

标签: php json foreach

我创建了一个手动循环来形成一个json,我正在开始的项目中使用另一个API,请在下面找到。

问题是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 ['hits'])的输出如下所示:

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

1 个答案:

答案 0 :(得分:3)

不要手动生成JSON。构建数组,然后使用SUM(B1:OFFSET(B10,-1,0))

json_encode()

DEMO

注意手工构造的JSON数组和对象的元素如何直接映射到PHP数组。如果JSON包含:

$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);

相应的PHP是:

{ "something": "something else" }