简体   繁体   English

在隐藏输入中使用json_encode将php数组作为json元素传递

[英]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. 我正在尝试使用javascript中的数组,因此尝试将Json_encode我的php数组作为隐藏值。 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. 在您当前的代码中,php无法理解您尝试使用json_encode函数,只是看到$pic_array变量为array。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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