PHP 将对象转换为数组的数组

标签 php mysql mysqli

我有 3 个表,在加入名称并用此输出角色后

$encoded = array();
while($res = mysqli_fetch_assoc($result)) {
    echo json_encode($res);
}

我明白了

{"student_id":"1","student_name":"john","score_id":"1","score_type":"E","score_name":"England"}
{"student_id":"1","student_name":"john","score_id":"2","score_type":"B","score_name":"Brazil"}

现在我正在努力将它们转换成我想要的格式,客户端站点必须有这个

//json
[{
"student_id":"1",
"student_name":"john",
"scores": [{
        "score_id":"1",
        "score_type":"E",
        "score_name":"England"
    },{
        "score_id":"2",
        "score_type":"B",
        "score_name":"Brazil"
    }]
}]

挑战在于它与同一个人有重复的行。

最佳答案

使用数组 $encoded 处理输出,一旦构建完成,您就可以使用 JSON 打印它。

在此解决方案中,数组将按 student_id 索引,分数按 score_id 索引。如果是学生,则必须,如果是分数,则建议:

$encoded = array();
while($res = mysqli_fetch_assoc($result)) {
  // Student's details
  $encoded[$res['student_id']] = array(
      'student_id' => $res['student_id'],
      'student_name' => $res['student_name'],
  );
  // Student's score details
  $encoded[$res['student_id']]['scores'][$res['score_id']] = array(
      'score_id' => $res['score_id'],
      'score_type' => $res['score_type'],
      'score_name' => $res['score_name'],
  );
}
echo json_encode($encoded);

注意:这是一般性答案,因为我不知道 $res 中数据的确切结构。

关于PHP 将对象转换为数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48040470/

相关文章:

php - Twig:从配置文件中添加 Twig 扩展调试

mysql - 将触发器放入 MySQL 数据库以更新 Oracle 数据库?

php - 刷新后登录 session 被销毁

php - 如何确定 while 循环内 tep_db_fetch_array 的大小?

php - mysqli_stmt_get_result 替代 php 5.2.6

php - json_decode 使用 mysqli 返回数组 1

php - 使用 Zend 框架获取页面内容

php - 如何使用 phpunit api 请求发送 header ?

php - MySQL和PHP显示错误

mysql - 需要捕获bash命令输出