简体   繁体   中英

Passing a php array as a json element with json_encode in a hidden input

I'm trying to work with an array in javascript so I am trying to Json_encode my php array as a hidden value. This is giving me this error Notice: Array to string conversion in.. Is this not possible? Am I going about this wrong?

$pic_array = array();
$titles = array();
$descriptions = array();
while ($row = $result->fetch_assoc()) {
    $pic_array[$count] = $row['pic_url'];
    $titles[$count] = $row['title'];
    $descriptions[$count] = $row['description'];
    $count++;
}

echo "<input id='json_pics' type='hidden' value='json_encode($pic_array)'/>";

Proper code is

echo "<input id='json_pics' type='hidden' value='" . json_encode($pic_array) . "'/>";

In your current code php doesn't understand that you try to use json_encode function and just sees $pic_array variable which is array.

为了提高可读性,我建议使用printf插入json编码的字符串。

echo sprintf("<input id='json_pics' type='hidden' value='%s'/>", json_encode($pic_array));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM