build json array in php dynamically

前端 未结 4 944
借酒劲吻你
借酒劲吻你 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: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.

提交回复
热议问题