Первое размещение здесь и действительно нужна помощь. Относительно новый для php У меня есть массив, который я хотел бы перестроить. У меня есть предметы на высшем уровне со студентами в подгруппе. Я хотел бы изменить структуру так, чтобы студенты были на верхнем уровне с предметами в подмассиве.
$startingArray = [
[ "subject" => "Physics",
"student" => [
["id" => "00003", "Name" => "Peter", "email" => "peter@schooool.com",],
["id" => "00004", "Name" => "Mary", "email" => "mary@schooool.com",],
["id" => "00005", "Name" => "Jane", "email" => "jane@schooool.com",],
]
],
[ "subject" => "Chemistry",
"student" => [
["id" => "00003", "Name" => "Peter", "email" => "peter@schooool.com",],
["id" => "00004", "Name" => "Mary", "email" => "mary@schooool.com",],
["id" => "00005", "Name" => "Jane", "email" => "jane@schooool.com",],
]
],
[ "subject" => "Mathematics",
"student" => [
["id" => "00003", "Name" => "Peter", "email" => "peter@schooool.com",],
["id" => "00006", "Name" => "Fred", "email" => "fred@schooool.com",],
["id" => "00007", "Name" => "Wilma", "email" => "wilma@schooool.com",],
]
],
[ "subject" => "Biology",
"student" => [
["id" => "00004", "Name" => "Mary", "email" => "mary@schooool.com",],
["id" => "00006", "Name" => "Fred", "email" => "fred@schooool.com",],
["id" => "00008", "Name" => "Alison", "email" => "alison@schooool.com",],
]
]
];
Я хочу, чтобы мой новый массив был таким;
$endingArray = [
"students" => [
[ "id" => "00003",
"Name" => "Peter",
"email" => "peter@schooool.com",
"subjects" => [ "Physics", "Chemistry", "Mathematics", ],
],
[ "id" => "00004",
"Name" => "Mary",
"email" => "mary@schooool.com",
"subjects" => [ "Physics", "Chemistry", "Biology", ],
],
[ "id" => "00005",
"Name" => "Jane",
"email" => "jane@schooool.com",
"subjects" => [ "Physics", "Chemistry", ],
],
[ "id" => "00006",
"Name" => "Fred",
"email" => "fred@schooool.com",
"subjects" => [ "Mathematics", "Biology", ],
],
[ "id" => "00007",
"Name" => "Wilma",
"email" => "wilma@schooool.com",
"subjects" => [ "Mathematics", "Biology", ],
],
[ "id" => "00008",
"Name" => "Alison",
"email" => "alison@schooool.com",
"subjects" => [ "Physics", "Biology", ],
],
],
];
Iпробую 2 этапа процесса. Во-первых, создать новый массив студентов без предметов. Это прекрасно работает.
Затем я пытаюсь добавить предметы, но я знаю, что моя логика неверна, и код, который я имею, просто создает новую строку для каждого студента и каждого предмета.
foreach ( $startingArray as $row ) {
$students = $row['student'];
foreach ($students as $student) {
if (!in_array($student, $studentsArray)) {
$studentsArray[] = $student;
}
}
}
второй шаг просто производит мусор
$s1 = $student['id'];
foreach ($startingArray as $row) {
$subject = $row['subject'];
$students = $row['student'];
foreach ($students as $s2) {
if ($s2['id]'] = $s1) {
$student['subjects'] = $subject;
array_push($studentsArray, $student);
}
}
}
}
Любая помощь приветствуется!