从重复键值对创建php数组

时间:2018-05-13 17:45:22

标签: php arrays json

我有来自后端的json响应:

[{"studentID":"1","subjectID":"2","marks":65},
{"studentID":"1","subjectID":"3","marks":75},
{"studentID":"2","subjectID":"2","marks":80},
{"studentID":"2","subjectID":"3","marks":82},
{"studentID":"3","subjectID":"2","marks":"82"},
{"studentID":"3","subjectID":"3","marks":"75"}] 

但我希望这样:

[{"studentID":"1","subjectID":"2","marks":65,"subjectID":"3","marks":75},
{"studentID":"2","subjectID":"2","marks":80,"subjectID":"3","marks":82}
{"studentID":"3","subjectID":"2","marks":"82","subjectID":"3","marks":"75"}]

有关如何从给定数组实现此目的的任何想法吗?

1 个答案:

答案 0 :(得分:0)

如上所述,每个对象都不能有重复的键。您需要将其重建为可以使用的东西。这样的事情可能是:

$data = json_decode('[{"studentID":"1","subjectID":"2","marks":65},{"studentID":"1","subjectID":"3","marks":75},{"studentID":"2","subjectID":"2","marks":80},{"studentID":"2","subjectID":"3","marks":82},{"studentID":"3","subjectID":"2","marks":"82"},{"studentID":"3","subjectID":"3","marks":"75"}]');

$students = [];

foreach($data as $d) {
    // If entry for student does not exist, create it
    if(!isset($students[$d->studentID])) {
        $students[$d->studentID] = ["subjects" => []];
    }

    // Add data to correct subject
    $students[$d->studentID]['subjects'][$d->subjectID] = [
        "marks" => $d->marks
    ];
}

echo json_encode($students);

// Output is: {"1":{"subjects":{"2":{"marks":65},"3":{"marks":75}}},"2":{"subjects":{"2":{"marks":80},"3":{"marks":82}}},"3":{"subjects":{"2":{"marks":"82"},"3":{"marks":"75"}}}}

然后,您可以使用$students[studentID]['subjects'][subjectId]['marks']

访问您的数据