<?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",], ] ] ]; $newArray = []; foreach ($startingArray as $item) { foreach ($item['student'] as $student) { if (empty($newArray[$student['id']])) { $student['subjects'] = []; $newArray[$student['id']] = $student; } $newArray[$student['id']]['subjects'][] = $item['subject']; } } print_r($newArray);
You have javascript disabled. You will not be able to edit any code.