重构数组在PHP中

时间:2011-08-18 10:56:06

标签: php arrays multidimensional-array

我有以下源数组,我正在尝试使用group_name进行重组,以便为​​我提供下面的require输出。

任何帮助或指示赞赏。 谢谢,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] => 
    )
)

4 个答案:

答案 0 :(得分:-1)

这可以通过简单的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;
    }
}

答案 1 :(得分:-2)

如果新阵列的键顺序不那么重要:

$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;
    }
}

答案 2 :(得分:-2)

这样的事情:

$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;
}

答案 3 :(得分:-2)

$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;时,它会自动用空数组初始化。