我正在尝试合并多维数组中键的重复值。
$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',
)
);
在上面,我需要找到公共类并将它们的子合并到一个数组中。因此,预期输出如下:
Array
(
[0] => Array
(
[class] => one
[sub] => array( 'music', 'social', 'health', 'science', 'math' )
)
[1] => Array
(
[class] => two
[sub] => music
)
)
我正在努力实现这个结果,但我却一事无成2。
$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_push( $class_sub[ $sub['class'] ], $sub['sub'] );
} else {
$new[] = $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>";
在这里我得到了2子:
Array
(
[0] => Array
(
[class] => one
[sub] => 2
)
[1] => Array
(
[class] => two
[sub] => music
)
)
这是怎么回事2?我该如何达到预期的结果?谢谢。
慕的地10843
手掌心
慕工程0101907