0

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.

3
  • sounds like you should adjust the query to remove the dupe Commented Dec 31, 2017 at 6:30
  • With json you have encode or decode. Can be object or assoc. Commented Dec 31, 2017 at 7:50
  • Do you know Doctrine2 ORM? You define models (objects) with sub attributes and map those to database tables. Doctrine fetches the rows and builds the objects... In your case probably a student model with score sub objects. In some cases you don't use ORM because of performance reasons... But it makes it much easier to handle complex data structures. Commented Dec 31, 2017 at 9:11

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@GlobinHughes I have updated the code to reflect you post updates.
0

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

3 Comments

can avoid this line? $arr = $students[$res['contact_id']] ?? []; I'm not using php 7 yet.
your answer doesn't work, I tried it, I gave me 2 array
Sorry unexpected error, please try again later or contact JDoodle support.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.