使用计数器将记录分配给数组

Assign records to an array with the counter

我正在将记录分配给数组并将其作为关联数组输出到 JSON 中。 我正在尝试做的事情,连同每条记录的结果 return 计数器,例如

{user_id: "14", fname: "Nicol", lname: "Geo, pass: "1234", counter: "0"}

{user_id: "15", fname: "and", lname: "asds", pass: "2145", counter: "1"}

{user_id: "17", fname: "asdsds", lname: "gfer", pass: "5", counter: "2"}

<?php

      $json_array = array();

      $mysqli->use_result();

      while ($row = $res->fetch_object()) {
        $counter++; #count record set
        $json_array[] = $row; #assign records to the array
      }

     print_r( json_encode(array('result' => $json_array)) );

您可以尝试使用 mysqli_fetch_array() 获取每一行作为关联数组,并在此数组中添加一个项目作为 "counter" 值:

<?php
      // Output
      $json_array = array();

      // Fetch data
      $res = $mysqli->use_result();
      while ($row = $res->fetch_array(MYSQLI_ASSOC)) {
        $row[] = $counter++;
        $json_array[] = $row; #assign records to the array
      }

      // Echo output
      print_r(json_encode(array('result' => $json_array)) );
?>