PHP将对象转换为数组

时间:2017-12-31 06:17:46

标签: 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"
    }]
}]

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

2 个答案:

答案 0 :(得分:1)

使用数组$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中数据的确切结构。

答案 1 :(得分:0)

请找到以下代码,以获取问题中提到的json格式

$students = [];
$sampleData    = [
          [

              "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",
          ],
];
foreach ($sampleData as $res) {

    //if student not found by id then continue
    if (empty($res['student_id'])) {
        continue;
    }

    $student = [];
    //get the already exists student to add scores
    if(!empty($students[$res['student_id']])) {
       $student = $students[$res['student_id']];
    }


    //prepare the student array
    $student['student_id']             = $res['student_id'];
    $student['student_name']           = $res['student_name'];
    $student['scores'][]['score_id']   = $res['score_id'];
    $student['scores'][]['score_type'] = $res['score_type'];
    $student['scores'][]['score_name'] = $res['score_name'];

    $students[$res['student_id']] = $student;
}

echo json_encode(array_values($students));

希望这会有所帮助

您可以找到工作示例here