我有以下源数组,我正试图使用group_name对其进行重组,以获得下面所需的输出。
感谢任何帮助或建议。谢谢,Lk
来源:
Array
(
[field_a] => Array
(
[type] => text
[group_name] =>
)
[field_b] => Array
(
[type] => number_integer
[group_name] => group_other
)
[field_c] => Array
(
[type] => text
[group_name] =>
)
[field_d] => Array
(
[type] => link
[group_name] => group_web_links
)
[field_e] => Array
(
[type] => link
[group_name] => group_web_links
)
[field_f] => Array
(
[type] => text
[group_name] => group_web_links
)
)
输出:
Array
(
[group_other] => Array
(
[field_b] => Array
(
[type] => number_integer
[group_name] => group_other
)
)
[group_web_links] => Array
(
[field_d] => Array
(
[type] => link
[group_name] => group_web_links
)
[field_e] => Array
(
[type] => link
[group_name] => group_web_links
)
[field_f] => Array
(
[type] => text
[group_name] => group_web_links
)
)
[field_a] => Array
(
[type] => text
[group_name] =>
)
[field_c] => Array
(
[type] => text
[group_name] =>
)
)
这可以通过一个简单的foreach
循环来实现:
$start_array; // The array you want to convert
$end_array = array (); // The final array
foreach ($start_array as $index => $value) {
if (empty($value["group_name"])) {
$end_array[$index] = $value;
} else {
$end_array[$value["group_name"]][$index] = $value;
}
}
如果新数组的键顺序不那么重要:
$new_array = array();
foreach ($old_array as $key => $value) {
if (empty($value['group_name'])) $new_array[$key] = $value;
else {
if (!array_key_exists($value['group_name'], $new_array) $new_array[$value['group_name']] = array();
$new_array[$value['group_name']][$key] = $value;
}
}
类似这样的东西:
$array_dst = array();
foreach ($array_src as $group_key=>$group_data){
$group_name = $group_data['group_name'];
if (empty($array_dst[$group_name]))
$array_dst[$group_name] = array();
$array_dst[$group_name][$group_key] = $group_data;
}
$new_array = array();
foreach( $old_array as $field_id => $field ) {
if( $field[ 'group_name' ] == '' ) {
$new_array[ $field_id ] = $field;
} else {
$new_array[ $field[ 'group_name' ] ][ $field_id ] = $field;
}
}
我想那些反对投票的人这样做是因为我没有初始化$new_array[ $field[ 'group_name' ] ]
。好吧,这在PHP中是不必要的,当您执行$new_array[ $field[ 'group_name' ] ][ $field_id ] = $field;
时,它将自动用一个空数组初始化。