<?php
$subjects = array(
array(
'class' => 'one',
'sub' => 'music',
),
array(
'class' => 'one',
'sub' => array( 'social', 'health', 'science' ),
),
array(
'class' => 'two',
'sub' => 'music',
),
array(
'class' => 'one',
'sub' => 'math',
)
);
$class_sub = array();
$result = array();
foreach( $subjects as $sub ) {
if ( ! isset( $class_sub[ $sub['class'] ] ) ) {
$class_sub[ $sub['class'] ] = $sub['sub'];
} else {
if ( is_array( $class_sub[ $sub['class'] ] ) ) {
$new = array_merge( $class_sub[ $sub['class'] ], is_array($sub['sub']) ? $sub['sub'] : array($sub['sub']));
} else {
$new = array_merge( array($class_sub[ $sub['class'] ]), is_array($sub['sub']) ? $sub['sub'] : array($sub['sub']));
}
$class_sub[ $sub['class'] ] = $new;
}
}
foreach( $class_sub as $class => $sub ) {
$result[] = array(
'class' => $class,
'sub' => $sub
);
}
echo "<pre>"; print_r( $result ); echo "</pre>";
preferences:
24.26 ms | 405 KiB | 5 Q