简体   繁体   中英

access JSON array elements coming from PHP

I have

{"user_id":"2790","freelancer_name":"","order_id":"8895","orderamount":"33638.00","payment_method":"","payment_desc":"","order_st":"newlink","total_comission":"3046.08","auto_increment_id":"2","po_box":"","country":"","order_add":"","shipping_co":"","weight":"0","fname":"","lastname":"","shippingcost":"0.00","paymentst":""}

{"user_id":"2790","freelancer_name":"","order_id":"9121","orderamount":"0.00","payment_method":"","payment_desc":"","order_st":"newlink","total_comission":"0.00","auto_increment_id":"1","po_box":"","country":"","order_add":"","shipping_co":"","weight":"0","fname":"","lastname":"","shippingcost":"0.00","paymentst":""}

coming from this PHP code

$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
    $myjsons[$i] = json_encode(array($row));
$myjsons[$i] = substr($myjsons[$i], 1, -1);

    $i++;
}


echo json_encode($myjsons);

I am trying to have access to each element but it seems that the array is just a string and doesn't have elements like user_id - order_id

here is the javascript to read the JSON

$("#txtfld").val(data[0]);
$("#resultTXT").val(data[1]);

I want have them like

txtfld = data[0].user_id and resultTXT = data[0].order_id ...

so the problem is to get the user id order id and etc

If you are using json_encode again (as in your echo statement) before returning the result to the user, for this line...

$myjsons[$i] = json_encode(array($row));

...don't json_encode inside the loop. You are double-encoding. It also appears you will not want to use array() here. So just do:

$myjsons[$i] = $row;

Actually, you can just do:

$myjsons[] = $row;

And get rid of:

$myjsons[$i] = substr($myjsons[$i], 1, -1);

Also, as someone pointed out in the comments, you'll want to use var obj = JSON.parse(data); on the client-side, though you'll probably want to conditionally add a library version of JSON where it is not supported (eg, this one ) since it is not supported in older browsers.

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