javascript - Unable to read properly from JSON file with php -
i trying read json file php array , echo array's content, can fetch info ajax
in javascript , convert array in javascript array of json objects.
here how json file looks like.
[["{\"id\":1474541876849,\"name\":\"d\",\"price\":\"12\"}"],["{\"id\":1474541880521,\"name\":\"dd\",\"price\":\"12\"}"],["{\"id\":1474541897705,\"name\":\"dddgg\",\"price\":\"124\"}"],["{\"id\":1474541901141,\"name\":\"faf\",\"price\":\"124\"}"],["{\"id\":1474543958238,\"name\":\"tset\",\"price\":\"6\"}"]]
here php :
<?php $string = file_get_contents("products.json"); $json_a = json_decode($string, true); $arr = array(); foreach ($json_a $key) { array_push($arr,$key[0]); } foreach ($arr $key) { echo $key; } ?>
and getting on client side :
{"id":1474541876849,"name":"d","price":"12"}{"id":1474541880521,"name":"dd","price":"12"}{"id":1474541897705,"name":"dddgg","price":"124"}{"id":1474541901141,"name":"faf","price":"124"}{"id":1474543958238,"name":"tset","price":"6"}
it looks not far, can can make json object?
please help!
the problem have json inside json.
you have decode twice:
<?php $string = file_get_contents("products.json"); $json_a = json_decode($string, true); //here turn json-string array containing json-strings $arr = array(); foreach ($json_a $key) { array_push($arr,json_decode($key[0],true)); //and here turn each of json-strings objects } echo json_encode($arr);
gives me this:
[{ "id": 1474541876849, "name": "d", "price": "12" }, { "id": 1474541880521, "name": "dd", "price": "12" }, { "id": 1474541897705, "name": "dddgg", "price": "124" }, { "id": 1474541901141, "name": "faf", "price": "124" }, { "id": 1474543958238, "name": "tset", "price": "6" }]
which valid json , want.
Comments
Post a Comment