我有一个 selectAll 函数,它将结果作为对象返回。
$customers = $app['database']->selectAll('customers');
这里是 $customers 变量的 var_dump 以防万一:
array(4) {
[0]=> object(stdClass)#5 (7) { ["id"]=> string(2) "10" ["name"]=> string(10) "Thisted El" ["address"]=> string(13) "Otto Monsteds" ["city"]=> string(5) "Vej 8" ["phone"]=> string(9) "503982350" ["zip"]=> string(6) "481922" ["notes"]=> string(0) "" }
[1]=> object(stdClass)#6 (7) { ["id"]=> string(2) "11" ["name"]=> string(11) "Bibin Vinod" ["address"]=> string(8) "Kottayam" ["city"]=> string(5) "Kochi" ["phone"]=> string(10) "0294294022" ["zip"]=> string(6) "129042" ["notes"]=> string(0) "" }
}
我需要将这些对象的“名称”属性用于自动填写表单。我在 this link 中使用自动完成脚本.
在我的 php 文件中,我在表单后添加了上述自动填充功能。然后我在这个对象上使用 json_encode,然后是 JSON.parse。我使用循环将名称仅添加到 javascript 数组,最后将其传递给自动完成函数。
var js_data = '<?php echo json_encode($customers); ?>';
var js_obj = JSON.parse(js_data);
for (var i = 0; i < arrayLength; i++)
{
customername[i] = js_obj["name"];
}
autocomplete(document.getElementById("customers"), customername);
但是自动填充表单不起作用。我需要有关此问题的帮助。谢谢。
最佳答案
我已经解决了这个问题。首先,我将对象数组转换为 PHP 中的普通数组:
$customers = $app['database']->selectAll('customers');
$allCustomers = array();
foreach($customers as $key => $val)
{
$allCustomers[] = $val;
}
然后在 javascript 部分,我对这个变量使用了 json encode
,并使用 for 循环将每个 'name' 属性添加到一个 javascript 数组,最后同样将它传递给自动完成函数:
var js_data = <?php echo json_encode($allCustomers) ?>;
var customername = [];
for (var i = 0; i < js_data.length; i++)
{
customername[i] = js_data[i]["name"];
}
autocomplete(document.getElementById("customers"), customername);
非常感谢大家提供的帮助。
关于javascript - 将 php 对象转换为 javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50346868/