如何在php中基于数组键将数组分解为子数组

时间:2015-03-10 16:18:54

标签: php arrays

我有下面的数组,我从多个表单提交,我必须根据键将此数组拆分为子数组

我从多个表单提交中得到的数组是:

Array
(
    [name_1] => sam
    [email_1] => sam@gmail.com
    [adress_1] => #224,us-west
    [phone_1] => 0144875954
    [city_1] => sanfransico
    [state_1] => us
    [country_1] => us
    [name_4] => ram
    [email_4] => ram@gmail.com
    [adress_4] => #444,india
    [phone_4] => 9844875954
    [city_4] => delhi
    [state_4] => delhi
    [country_5] => india
    [name_5] => jam
    [email_5] => jam@gmail.com
    [adress_5] => #224,cannada
    [phone_5] => 0344875954
    [city_5] => sanfransico
    [state_5] => cannada
    [country_5] => cannada
    [name_7] => kam
    [email_7] => kam@gmail.com
    [adress_7] => #224,us-east
    [phone_7] => 0144875954
    [city_7] => california
    [state_7] => us
    [country_7] => us

)

我希望将上面的数组分解为如下所示的子数组,我的意思是从name_1到country_1一个数组再次将name_4改为country_4另一个数组如此...我从多个表单提交中动态获取此数组

Array
(
    [0] => Array
        (
            [name] => sam
            [email] => sam@gmail.com
            [adress] => #224,us-west
            [phone] => 0144875954
            [city] => sanfransico
            [state] => sanfransico
            [country] => us
        )

    [1] => Array
        (
            [name] => ram
            [email] => ram@gmail.com
            [adress] => #444,india
            [phone] => 9844875954
            [city] => delhi
            [state] => delhi
            [country] => india
        )

    [2] => Array
        (
            [name] => jam
            [email] => jam@gmail.com
            [adress] => #224,cannada
            [phone] => 0344875954
            [city] => sanfransico
            [state] => cannada
            [country] => cannada
        )

    [3] => Array
        (
            [name] => kam
            [email] => kam@gmail.com
            [adress] => #224,us-east
            [phone] => 0144875954
            [city] => california
            [state] => us
            [country] => us
        )
)

这就是我的尝试:

foreach ($arr as $k_fmt => $v_fmt) { 
    $arr_fetch = explode("_", $k_fmt, 2); 
    $ele_key = $arr_fetch[0]; 
}

1 个答案:

答案 0 :(得分:0)

你开始正确,但是在分开钥匙后你从未做过任何事情。设置变量不会将其添加到结果数组中。

$new_arr = array();
foreach ($arr as $k_fmt => $v_fmt) {
    $arr_fetch = explode("_", $k_fmt, 2); // Split up they key at the _ character
    $ele_key = arr_fetch[0];
    $ele_index = arr_fetch[1] - 1; // Because original keys start at 1, not 0
    if (!isset($new_arr[$ele_index])) { // Create sub-array if necessary
        $new_arr[$ele_index] = array();
    }
    $new_arr[$ele_index][$ele_key] = $v_fmt; // Use the split up key as the indexes in 2-dimensional result
}