使用php格式化json对象

ncf

我正在尝试使用php对json响应进行编码,并且在格式化使其与ajax结合使用时遇到一些麻烦。

基本上,我试图返回租赁对象,每个将包括数据的阵列bookstudentteacher目前,我正在使用php来构建这样的对象...

while ($row = $result->fetch_array(MYSQLI_BOTH)) {
        $obj = array();

        // Build a book out of the results array, then push to the current object
        $book = new Book();
        $book->id = $row['book_id'];
        $book->title = $row['title'];
        $book->author = $row['author'];
        $book->ar_quiz = $row['ar_quiz'];
        $book->ar_quiz_pts = $row['ar_quiz_pts'];
        $book->book_level = $row['book_level'];
        $book->type = $row['type'];
        $book->teacher_id = $row['teacher_id'];
        array_push($obj, array('book' => $book));

        // Build a student out of the results array, then push it to the current objects
        $student = new Student();
        $student->id = $row['student_id'];
        $student->username = $row['student_username'];
        $student->nicename = $row['student_nicename'];
        $student->classroom_number = $row['classroom_number'];
        array_push($obj, array('student' => $student));


        // Build a teacher out of the results, push to current object
        $teacher = new Teacher();
        $teacher->id = $row['teacher_id'];
        $teacher->username = $row['teacher_username'];
        $teacher->nicename = $row['teacher_nicename'];
        array_push($obj, array('teacher' => $teacher));

        array_push($rentals, $obj);
    }

    mysqli_stmt_close($stmt);
    return json_encode($rentals);

...为每个结果构建一个$ obj,然后将整个$ obj对象附加到$ rentals的末尾,这就是我最后返回的内容。当我将其编码为json时,响应如下所示:

   [  
      [  
        {  
           "book":{  
              "id":113,
              "title":"Book Test",
              "author":"Test Test Author",
              "ar_quiz":1,
              "ar_quiz_pts":"10.0",
              "book_level":"20.0",
              "type":"Fiction",
              "teacher_id":1
           }
        },
      {  
           "student":{  
              "id":2,
              "username":"studentnametest",
              "classroom_number":2,
              "nicename":"Student Name"
           }
      },
    ],
    ...
  ]

这里的问题是,有一个额外的{}各地各的bookstudentteacher对象,试图在JavaScript访问时,造成额外的步骤。例如,data[0].[0].book.title当我真的只想能够使用时,我认为我必须使用data[0].book.title我如何更好地构造它以满足我的需求?

钱德勒躁狂症

不要添加额外的数组结构,您只需更改array_push行即可

array_push($obj, array('book' => $book));

$obj['book'] =  $book;

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章