I have a two dimensional array of students from different schools and countries. I want them to be grouped by name of school and country.
How can I create the nested key structure?
Example:
$students = [
[
"country" => "japan",
"school" => "kyoto university",
"name" => "Naruto Uzumaki"
],
[
"country" => "usa",
"school" => "harvard university",
"name" => "Naruto Uzumaki"
],
[
"country" => "japan",
"school" => "tokyo university",
"name" => "sasuke Uchiha"
],
[
"country" => "japan",
"school" => "tokyo university",
"name" => "kakashi hatake"
],
];
Desired result:
[
“japan” => [
“kyoto university” => [
[
“country” => “japan”,
“school” => “kyoto university”,
“name” => “Naruto Uzumaki”
],
],
“tokyo university” => [
[
“country” => “japan”,
“school” => “tokyo university”,
“name” => “sasuke Uchiha”
],
[
“country” => “japan”,
“school” => “tokyo university”,
“name” => “kakashi hatake”
],
],
],
“usa” => [
“harvard university” => [
[
“country” => “usa”,
“school” => “harvard university”,
“name” => “Naruto Uzumaki”
],
]
]
]
2
Answers
Pretty much creating an object or using an existing one. First create country object if not exists, then create school object under it (if not exists) then push to it.
Output:
extract()
Code: (Demo)
It is not at all necessary to instantiate/declare parent elements before pushing child elements when using square brace pushing syntax. If you are using
array_push()
, the parent element must be declared in advance.There are more abstract and less attractive ways to code this task using
array_reduce()
or array destructuring:Related: