简体   繁体   English

将PHP中的两个单独的数组合并为一个数组

[英]joining two separate arrays in PHP into one array

i have a piece of code that joins two arrays together in PHP like this 我有一段代码将两个数组像这样在PHP中连接在一起

    $array_1=[1,2,3,4]; //input 1
    $array_2= ["a","b","c","d"];//input 2
    $array_3= ["1 a", "2 b", "3 c", "4 d"]; //this is how my final array should look like

i tried using array merge but it did not do what i wanted it to do is there another function i can use to do this. 我尝试使用数组合并,但没有执行我想要的操作,还有另一个可以用来执行此操作的功能。

so basically i am trying to get the numbers from the array 1 and letters from the array 2 and join it together in array 3 in to a single array 所以基本上我想从array 1获取数字,从array 2获取字母,并将其在array 3中连接在一起,形成一个数组

You can just map the 2 arrays 您可以map两个数组

$array_1 = array(1,2,3,4);
$array_2 = array('a','b','c','d');

$array_3 = array_map(function($a1, $a2) {
    return $a1 . " " . $a2;
}, $array_1, $array_2);

echo "<pre>";
print_r( $array_3 );
echo "</pre>";

This will result to: 这将导致:

Array
(
    [0] => 1 a
    [1] => 2 b
    [2] => 3 c
    [3] => 4 d
)
<?php
$array_1=[1,2,3,4]; //input 1
$array_2= ['a','b','c','d'];//input 2

for($i=0;$i<count($array_1);$i++){
    $newArray[]=$array_1[$i].' '.$array_2[$i];
}

echo '<pre>';
print_r($newArray);

And the output is : 输出为:

Array
(
    [0] => 1 a
    [1] => 2 b
    [2] => 3 c
    [3] => 4 d
)

Probably this is what you need. 可能这就是您所需要的。 I assume that both of arrays contains equal quantity of elements. 我假设两个数组都包含相等数量的元素。

function merge($array1, $array2) {
    $retArray = [];

    foreach ($array1 as $index => $value) {
        $retArray[] = $value . ' ' . $array2[$index];
    }

    return $retArray;
}

$array_1 = [1,2,3,4];
$array_2 = ["a", "b", "c", "d"];
$array_3 = merge($array_1, $array_2);

var_dump($array_3);

The result is: 结果是:

array(4) {
  [0]=>
  string(3) "1 a"
  [1]=>
  string(3) "2 b"
  [2]=>
  string(3) "3 c"
  [3]=>
  string(3) "4 d"
}
$array_1=[1,2,3,4];
$array_2= ["a","b","c","d"];
$array_3 = [];
for ($i = 0; $i < min(count($array_1), count($array_2)); $i++) {
    array_push($array_3, sprintf("%d %s", $array_1[$i], $array_2[$i]));
}
var_dump($array_3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM