通过键将3个一维数组合并成一个多维数组

时间:2016-10-19 07:04:10

标签: php arrays

所以我有3个数组。一个包含用户的名字,第二个包含用户的姓氏,第三个包含他们的姓氏。

数组有一个共同点,即键....所以user_first [0]属于user_last [0],它也与email [0]匹配,依此类推。

所以我想要一个新的数组:

Array
(
  [0] => Array
  (
    [first_name] => John
    [last_name] => Doe
    [email] => john.doe@domain.com
  )

  [1] => Array
  (
    [first_name] => Jane
    [last_name] => Doe
    [email] => jane.doe@domain.com
  )

)

而不是原始的,这将是:

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

3 个答案:

答案 0 :(得分:0)

$combinedArray = array();

foreach($first_names as $key => $first_name)
{
  $combinedArray[$key] = array(
    "first_name" = $first_name,
    "last_name" = $last_names[$key],
    "email" = $emails[$key]
  );
}

答案 1 :(得分:0)

只需在数组中使用数组,如

    $a = array();
    $a[] = array("first_name"=>"John","last_name" => "Doe", "email" => "john.doe@domain.com");
$a[] = array("first_name"=>"Jane","last_name" => "Doe", "email" => "jane.doe@domain.com");

这正是你想要的,即

array(2) {
  [0]=>
  array(3) {
    ["first_name"]=>
    string(4) "John"
    ["last_name"]=>
    string(3) "Doe"
    ["email"]=>
    string(19) "john.doe@domain.com"
  }
  [1]=>
  array(3) {
    ["first_name"]=>
    string(4) "Jane"
    ["last_name"]=>
    string(3) "Doe"
    ["email"]=>
    string(19) "jane.doe@domain.com"
  }
}

答案 2 :(得分:0)

尝试使用以下代码

<?php 
$arr1 = array(
              0 => "John",
              1 => "Jane");

$arr2 = array
(
  0 => "Doe",
  1 =>  "Doe"
);
$arr3 =array
(
  0 => "john.doe@domain.com",
  1 => "jane.doe@domain.com"
);
$new_arr=[];
foreach ($arr1 as $key => $value) {
    # code...
    //echo $arr2[$key]."<br>";

    $new_arr[$key]["first_name"]= $value;
    $new_arr[$key]["last_name"]= $arr2[$key];
    $new_arr[$key]["email"]= $arr3[$key];
}

echo "<pre>";
print_r($new_arr);

在此处查看演示:demo