Professor Zoom Professor Zoom - 1 year ago 85
JSON Question

How to convert an object from PHP to an Array in Javascript?

I'm trying to convert an object that I get from PHP into an array in Javascript but I don't know how to solve this, I try some solutions I read before do this question but it doesn't work, I got something like this in PHP

$data = explode(',', $articles);

$length = count($data);

for ($i = 0; $i < $length; $i++) {

$products = explode('-', $data[$i]);

$product_key = $products[0];
$quantity = $products[1];

$get_data_product = mysqli_query($connection, "SELECT * FROM articles WHERE id_article = '".$product_key."' AND id_user = '".$id_user."'") or die (mysqli_error($connection));
$get_data_product = mysqli_fetch_assoc($get_data_product);
$article_name = $get_data_product['name'];
$article_price = $get_data_product['price'];

$info[$i] = array('name' => $article_name, 'quantity' => $quantity, 'price' => $article_price);

echo json_encode($info);

And in Javascript

success: function(info) {

var data = JSON.stringify(info);


Console log show this

[{"name":"prueba 2","quantity":"4","price":"100"}]

I tried to read them all with ths code but it is showing data, only when I use console log or alert

$.each(data, function(i) {

$('#content').append('<tr class="text-center">' +
'<td>' + data[i].quantity + '</td>' +
'<td>' + data[i].name + '</td>' +


Answer Source

As prodigitalson notes in the comments - and is effectively the answer - you converted your data into a JSON object in PHP, but then convert it needlessly into a string, so you then can't manipulate it at all.

E.g: JSON.stringify([{test: 1}]) becomes "[{test: 1}]".

Removing that, you will then be able to loop on it in your original way, or you can loop on it using a standard javascript foreach where data is your response in your callback containing [{"name":"prueba 2","quantity":"4","price":"100"}]:

data.forEach(function (e) {
        '<tr class="text-center">\n' +
            '<td>' + e.quantity + '</td>\n' +
            '<td>' + + '</td>\n' +
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download