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

时间:2019-05-18 13:21:52

标签: php arrays associative-array

我正在将记录分配给该数组,并以JSON作为关联数组输出。 我正在尝试做的事情,以及每条记录的结果以返回计数器,例如

{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)) );

1 个答案:

答案 0 :(得分:3)

您可以尝试使用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)) );
?>