One option is to use array_reduce
to group the array into an associative array and use subjectId
as the key. Use array_values
to convert the associative array into a simple array.
$result = array_reduce($arr, function($c, $v){
if ( !isset( $c[$v['subjectId']] ) ) $c[$v['subjectId']] = array( 'subjectId'=> $v['subjectId'], 'subjectName' => $v['subjectName'], 'chapters' => array() );
$c[$v['subjectId']]['chapters'][] = array( 'chapterId' => $v['chapterId'], 'chapterName' => $v['chapterName']);
return $c;
}, array());
$result = array_values( $result );
This will result to:
Array
(
[0] => Array
(
[subjectId] => 13
[subjectName] => Chemistry
[chapters] => Array
(
[0] => Array
(
[chapterId] => 1
[chapterName] => Chem 1
)
[1] => Array
(
[chapterId] => 2
[chapterName] => Chem 2
)
)
)
[1] => Array
(
[subjectId] => 14
[subjectName] => Mathematics
[chapters] => Array
(
[0] => Array
(
[chapterId] => 5
[chapterName] => Math 1
)
[1] => Array
(
[chapterId] => 6
[chapterName] => Math 2
)
)
)
)
1
solved php convert mulitdimentional array