使用一维数组,将其展开,并创建一个多维数组

So I have an array that looks like this:

Array
 (
  [0] => john.smith@domain.com:John
  [1] => jane.doe@domain.com:Jane
)

As you can see, it's user'semail and user's name, seperated by a colon.

I want to create a multi dimensional array, that explodes the colon, and then will create a multi dimensional array that would look more like

Array
 (
   [0] => Array
    (
        [user_email] => john.smith@domain.com
        [user_name] => John
    )

   [1] => Array
    (
        [user_email] => jane.doe@domain.com
        [user_name] => Jane
    )

)

You can do it like:

<?php

$data = [
    "john.smith@domain.com:John",
    "jane.doe@domain.com:Jane"
];

function customArray($data){
    $final = [];
    $i = 0;

    foreach($data as $k => $v){
        $splitted = explode(":",$v);
        $final[$i]['user_email'] = $splitted[0];
        $final[$i]['user_name']  = $splitted[1];
        $i++;
    }

    return $final;
}

print_r(customArray($data));

See the results here. Basically what I do above is

  • iterate over the array,
  • explode the value by the delimiter :,
  • index them within the iteration using the same [$i] so that the new key/value is paired correctly per original array element.

Do properly name things though, I'm just giving an example :-)

You can explode the every element of source array and save it in a new array like below. Finally, you will be getting the desired format in $result array.

$source_array = array("john.smith@domain.com:John","jane.doe@domain.com:Jane");
foreach($name_email_array as $key => $value){
        $name_email = explode(":",$value);
        $result[$key]['user_email'] = $name_email[0];
        $result[$key]['user_name']  = $name_email[1];
    }