合并数组并为每个数组添加键

时间:2019-11-27 07:24:51

标签: php arrays laravel laravel-5

我只是找不到正确的问题

非常多的合并数组

$arr1 = ["temp1", "temp2", "temp3"];
$arr2 = [5, 7, 2];

对此

$combined = [["name" => "temp1", "number" => 5], ["name" => "temp2", "number" => 7], ["name" => "temp3", "number" => 2]];

除了foreach以外,还有其他以最有效的方式进行操作的想法吗?

4 个答案:

答案 0 :(得分:2)

$arr1 = ["temp1", "temp2", "temp3"];
$arr2 = [5, 7, 2];
foreach($arr1 as $key => $value)
{
  $r[$key]['name'] = $value;
        $r[$key]['number'] = $arr2[$key];
    }
  print_r($r);

答案 1 :(得分:1)

您可以使用foreach循环,

$result = [];
foreach($arr1 as $key => $value){
    $resutl[] = array("name"=>$value,"number"=>$arr2[$key]);
}

答案 2 :(得分:1)

您可以执行以下代码来获取结果

$arr1 = ["temp1", "temp2", "temp3"];
$arr2 = [5, 7, 2];
$count = count($arr1);
$combined = array();
for($i=0;$i<$count;$i++){
    $combined[$i]['name'] = $arr1[$i];
    $combined[$i]['number'] = $arr2[$i];
}

答案 3 :(得分:1)

内置函数array_map实际上可以用于多个数组:

$result = array_map(function($value1, $value2) {
    return ["name" => $value1, "number" => $value2];
}, $arr1, $arr2);

Here are与简单的foreach进行比较的一些基准