[英]Change the format of JavaScript array when source is PHP
I am currently working on laravel and my project requires me to use autocomplete for dropdowns. 我目前正在研究laravel,我的项目要求我对下拉菜单使用自动完成功能。
However, the object returned from the following 但是,对象从以下返回
$companies = Companies::all()->pluck('company_name','id')->toArray();
and converted to js array using the following 并使用以下内容转换为js数组
var companies = <?php echo json_encode($companies) ?>;
returns the following format of array 返回数组的以下格式
{ 2: "Jadon Technology",
58: "Samsung",
59: "Sony",
60: "Sujan",
61: "Superman",
68: "Vivo",
84: "Iphone",
85: "Oppo",
}
I want the array as given below. 我想要下面给出的数组。
var companies = [
{ id: 2, value: "Jadon Technology"} ,
{ id: 58, value: "Samsung"} ,
{ id: 59, value: "Sony"} ,
{ id: 60, value: "Sujan"} ,
{ id: 61, value: "Superman"} ,
{ id: 68, value: "Vivo"} ,
{ id: 84, value: "Iphone"} ,
{ id: 85, value: "Oppo"} ,
];
Am i doing something wrong or is there any other way to convert into said format? 我是在做错什么,还是有其他方法可以转换成上述格式? Please someone help me.
请有人帮我。 Suggestions including php/laravel/javascript oriented are welcomed.
欢迎包括php / laravel / javascript在内的建议。 PS: no foreach loop because i have to implement the same in numerous places in the same project.
PS:没有foreach循环,因为我必须在同一项目的许多地方实现相同的功能。
Why not implement a function to do the work, then call the function before json_encode: 为什么不实现一个函数来完成工作,然后在json_encode之前调用该函数:
function convert($arr) {
$tmp = array();
foreach ($arr as $k => $v) {
$tmp[] = array("id" => $k, "value" => $v)
}
return $tmp;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.