手动创建的 JSON 字符串无效

问题描述 投票:0回答:1

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

问题是 API 无法识别我的 json 输出。我检查了循环的结果,看起来不错。

如果我直接复制并粘贴我的结果(echo),它工作正常,但通过我的循环,它不起作用。有人有什么想法吗?

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 ....
php json foreach
1个回答
5
投票

不要手动生成 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);

演示

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

{ "something": "something else" }

对应的PHP是:

array("something" => "something else")
© www.soinside.com 2019 - 2024. All rights reserved.