使用php格式化json对象

时间:2014-08-22 17:44:20

标签: php json

我正在尝试使用php编码json响应,并且在将其格式化以便与ajax一起使用时遇到一些麻烦。

我基本上是在尝试返回一组Rental对象,每个对象都包含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对象附加到$ rental的末尾,这是我最后传回的内容。以下是我将其编码为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时。我如何更好地构建它以满足我的需求?

1 个答案:

答案 0 :(得分:3)

不要添加额外的数组结构,只需从

更改array_push行即可
array_push($obj, array('book' => $book));

$obj['book'] =  $book;