简体   繁体   English

将php数组转换为javascript数组

[英]convert php array to a javascript array

I am working with laravel, and i get a list of values from a database with this code: 我正在使用laravel,我使用以下代码从数据库中获取值列表:

$idordenes = DB::table('ordenes')->select('id')->get();

when I echo de idordenes variable I get this: 当我回应de idordenes变量时,我得到这个:

[{"factoryid":233658},{"factoryid":566981},{"factoryid":889566},{"factoryid":114789},{"factoryid":256958},{"factoryid":0},{"factoryid":0},{"factoryid":599544},{"factoryid":222364},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":555696},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},

I want to covert this in a javascript array like this: 我想在这样的javascript数组中隐藏它:

var ordenes = [233658,566981,889566,114789,...];

I hope the help. 我希望得到帮助。 thanks 谢谢

Try this: 尝试这个:

 const arr = [{"factoryid":233658},{"factoryid":566981},{"factoryid":889566},{"factoryid":114789},{"factoryid":256958},/* more element */]; let newArr = arr.map(elem=>elem.factoryid); console.log(newArr); 

But your mean is code in php or js ? 但你的意思是phpjs代码?

You need to use an ajax get request to get the data from php to your javascript file. 您需要使用ajax get请求将数据从php获取到您的javascript文件。 You can use jQuery to make an ajax request like so: 您可以使用jQuery来生成ajax请求,如下所示:

$.ajax(
  url: "path_to_your_php_file",
  success: data => {
    var ordenes = JSON.parse(data);
    console.log(ordenes); // Ordenes is now the array in javascript
  }
);

In your php file you must "send out" the data you wish the ajax call to receive. 在您的php文件中,您必须“发送”您希望ajax调用接收的数据。 You can do this by doing the following: 您可以通过执行以下操作来执行此操作:

echo json_encode(array_column($idordenes, 'factoryid'));

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

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