PHP将对象转换为数组数组

I have 3 tables, after joining name and output the role with this

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

I got this

{"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"}

Now I'm struggling to turn them into the format I wanted, the client site have to have this

//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"
    }]
}]

The challenge is it has duplicated row with the same person.

Process the output using the Array $encoded and once it is built then you can print it with JSON.

In this solution the array will be indexed by student_id and the scores by score_id. In case of student it is a must, in case of scores it is recommended:

$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);

Note: this is general answer since I do not know exact structure of your data in $res.

Please find the below code to get the json format as mentioned in your question

$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));

hope this helps

You can find the working example here