如何在PHP中从两个一维数组创建一个二维数组?

时间:2017-03-21 16:19:23

标签: php multidimensional-array

我想将两个数组组合成一个二维数组。

$firstnames = array("Jim", "Jack", "Mary", "Betty");

$lastnames = array("Brown", "Smith", "Hughes", "Malone");

我想要一个数组$bothnames['firstname']['lastname'],我希望它能回显并用于稍后检查PID字段。

我已经尝试了所有我知道的填充二维数组并回应它。

// populate

$bothnames = array();

for ($i=0; $i<count($firstnames); $i++)
 { 
    $bothnames[$i] = array();
        for ($x=0; $x<count($lastnames); $x++)
        {
           $bothnames[$i][$x] = $lastnames[$x];
        }
 }


// echo

for ($i=0; $i<count($firstnames); $i++)
 { 
   for ($x=0; $x<count($lastnames); $x++)
    {
    echo $bothnames[$i][$x]; 
    echo "<br>";
    }

  }

这只是给出姓氏(和循环4次)。如何获得输出

Jim Brown
Jack Smith
etc.

4 个答案:

答案 0 :(得分:3)

您可以使用以下方法组合数组:

<?php
$firstnames = array("Jim", "Jack", "Mary", "Betty");
$lastnames = array("Brown", "Smith", "Hughes", "Malone");
$names = array();
$i = 0;
foreach($firstnames as $fn)
{
    $names[$fn] = $lastnames[$i];
    $i++;
}
echo "<pre>";
print_r($names);

稍后使用:

foreach($names as $first => $last)
{
    $firstName = $first;
    $lastName = $last;
}

需要注意的是,两个阵列的长度应该相同。

答案 1 :(得分:1)

使用array_combine函数

$firstnames = array("Jim", "Jack", "Mary", "Betty");
$lastnames = array("Brown", "Smith", "Hughes", "Malone");
$bothnames = array_combine($firstnames, $lastnames);

foreach($bothnames as $key=>$value){
    echo $key." ".$value;
    echo "<br/>";
}

答案 2 :(得分:1)

您应该学会利用PHP数组的强大功能。这是一个例子:

$firstnames = array("Jim", "Jack", "Mary", "Betty");
$lastnames = array("Brown", "Smith", "Hughes", "Malone");
$bothnames = array_map(function ($firstname, $lastname) {
       return [$firstname,$lastname];
}, $firstnames, $lastnames);

foreach ($bothnames as $fullname) {
     echo $fullname[0]." ".$fullname[1];
}

打印:

  

Jim Brown

     

杰克史密斯

     

Mary Hughes

     贝蒂马龙

array_map details

答案 3 :(得分:1)

如果您确定数组的长度相等

,请使用array_combine
$firstnames = ["Jim", "Jack", "Mary", "Betty"];
$lastnames = ["Brown", "Smith", "Hughes"];
$bothnames = array_combine($firstnames, $lastnames);

foreach ($bothnames as $key => $value) {
    echo $key . " " . $value;
    echo "\n";
}

或者如果您不确定此代码是否更安全

$firstnames = ["Jim", "Jack", "Mary", "Betty"];
$lastnames = ["Brown", "Smith", "Hughes", "Malone"];

foreach ($firstnames as $k => $v) {
    echo $v . (isset($lastnames[$k]) ? ' ' . $lastnames[$k] : '');
    echo "\n";
}