简体   繁体   中英

How to print data array using php json_encode

I want to print data like this using php json_encode so what the php code to output this data for using java script code .

var data = [{
"name": "test",
    "calories": "1000",
    "fat": "100",
    "protein": "100",
    "carbohydrates": "800",
 }, {
"name": "test2",
    "calories": "10000",
    "fat": "343",
    "protein": "3434",
    "carbohydrates": "4343",
 }];

I am try this php code but the data output not like i want.

<?PHP
 $RESULT = array();

 for($x=0;$x<=4;$x++){
   $RESULT["data"]["name"][]    = "Name" . $x;
   $RESULT["data"]["calories"][]    = "calories" . $x;
   $RESULT["data"]["fat"][]    = "fat" . $x;
   $RESULT["data"]["protein"][]    = "protein" . $x;
   $RESULT["data"]["carbohydrates"][]    = "carbohydrates" . $x;
 }

 echo $_GET['callback']."(".json_encode($RESULT).");";
?>

I want json_encode print the data like first code .

I'm not sure how you plan to use it or what you're doing with $_GET['callback'] , but the main issue is that you need to append elements under a new array under data :

for($x=0;$x<=4;$x++){
    $RESULT["data"][$x]["name"] = "Name" . $x;
    $RESULT["data"][$x]["calories"] = "calories" . $x;
    $RESULT["data"][$x]["fat"] = "fat" . $x;
    $RESULT["data"][$x]["protein"] = "protein" . $x;
    $RESULT["data"][$x]["carbohydrates"] = "carbohydrates" . $x;
}
echo json_encode($RESULT, JSON_PRETTY_PRINT);

So:

$RESULT["data"][$x]["name"]

Not:

$RESULT["data"]["name"][]

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