encode json using php?

前端 未结 5 1738
滥情空心
滥情空心 2020-12-06 07:33

I want to get json with php encode function like the following



        
相关标签:
5条回答
  • 2020-12-06 08:13

    If I were you, I would not json_encode each individual array, but merge the arrays together and then json_encode the merged array at the end. Below is an example using 5.4's short array syntax:

    $out = [];
    while(...) {
      $out[] = [ 'id' => $i, 'name' => $row['name'] ];
    }
    echo json_encode($out);
    
    0 讨论(0)
  • 2020-12-06 08:17

    build it all into an array first, then encode the whole thing in one go:

    $outputdata = array();
    while($row = mysql_fetch_array($result)) {
        $outputdata[] = $row;
    }
    
    echo json_encode($outputdata);
    
    0 讨论(0)
  • 2020-12-06 08:19

    Do the json_encoding as the LAST step. Build your data structure purely in PHP, then encode that structure at the end. Doing intermediate encodings means you're basically building your own json string, which is always going to be tricky and most likely "broken".

    $data = array();
    while ($row = mysql_fetch_array($result)) {
       $data[] = array('id'=>$i, 'name' => $row['name']);
    }
    echo json_encode($data);
    
    0 讨论(0)
  • 2020-12-06 08:22

    Just change that lines

    echo json_encode(array('id'=>$i, 'name' => $row['name']));
    echo ",";
    

    To these

    echo ",";
    echo json_encode(array('id'=>$i, 'name' => $row['name']));
    
    0 讨论(0)
  • 2020-12-06 08:27

    Here is a solution that i came with

     $i = 1; 
     $array = array(); 
     while($row = mysql_fetch_array($result)) 
     { 
     $array[] = json_encode(array('id'=>$i, 'name' => $row['name'])); 
     $i++; 
     } 
     echo implode(',', $array); // Take output array glue it with the  
    

    This will put the json into an array and then implode it with glue (,) outputing the following {"results":[{"id":1,"name":"maadi"},{"id":2,"name":"monofiya"}]} without the need to do the array first then pass it to the json_encode() function

    0 讨论(0)
提交回复
热议问题