【问题标题】:Formatting json object using php使用php格式化json对象
【发布时间】:2014-08-22 17:44:20
【问题描述】:

我正在尝试使用 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 对象附加到 $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。我如何更好地构建它以满足我的需求?

【问题讨论】:

    标签: php json


    【解决方案1】:

    不要添加额外的数组结构,你可以简单地改变你的 array_push 行

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

    $obj['book'] =  $book;
    

    【讨论】:

    • 太好了,正是我需要的。
    猜你喜欢
    • 1970-01-01
    • 2014-07-11
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    相关资源
    最近更新 更多