<?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>";
- Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.27, 8.3.0 - 8.3.15, 8.4.1 - 8.4.2
- <pre>Array
(
[0] => Array
(
[class] => one
[sub] => Array
(
[0] => music
[1] => social
[2] => health
[3] => science
[4] => math
)
)
[1] => Array
(
[class] => two
[sub] => music
)
)
</pre>
preferences:
133.85 ms | 408 KiB | 5 Q