简体   繁体   中英

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:

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

when I echo de idordenes variable I get this:

[{"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:

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 ?

You need to use an ajax get request to get the data from php to your javascript file. You can use jQuery to make an ajax request like so:

$.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. You can do this by doing the following:

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

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