build json array in php dynamically

前端 未结 4 922
借酒劲吻你
借酒劲吻你 2021-02-13 21:15

I can create simple json objects like this:

$d = array(\'item\' => \"$name\" ,\'rate\' => \"$rating\");

But what if I want to build an ar

相关标签:
4条回答
  • 2021-02-13 22:04

    Why not create your array as you just have done but then pass the array through json_encode?

    If you want a multi-dimensional array, try

    $array[] = array("key1" => value1, "key2" => value2);
    
    0 讨论(0)
  • 2021-02-13 22:10

    But I want multiple json objects in a json array when i encode it.

    Then create an array of arrays and pass it to json_encode. The documentation about arrays explains how to add elements to an array, in the section Creating/modifying with square bracket syntax.

    Associative arrays, like the one you already have, will be encoded as objects, "normal" arrays (arrays with consecutive numerical keys) will be encoded as arrays.

    Example:

    $d = array();
    
    // This appends a new element to $d, in this case the value is another array
    $d[] = array('item' => "$name" ,'rate' => "$rating");
    
    $json = json_encode($d);
    
    0 讨论(0)
  • 2021-02-13 22:10

    What you can do is create a php array dynamically as you want then covert it into a json array as below.

    $json_array = json_encode($array);
    

    Keep in mind that what you have provided is not a json array

    0 讨论(0)
  • 2021-02-13 22:15

    This will create a multi-dimensional array from your database query, and then encode it as JSON.

    $d = array();
    while ($row = $stmt->fetch_assoc()) {
      $d[] = $row;
    }
    $json = json_encode($d);
    

    Each $row will be an associative array of the data returned from the database. Assigning it to $d[] adds it as an indexed element of that container array.

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