PHP - 将两个数组(相同长度)合并为一个关联?

时间:2021-10-25 11:42:14

pretty straightforward question actually..

实际上很简单的问题..

is it possible in PHP to combine two separate arrays of the same length to one associative array where the values of the first array are used as keys in the associative array?

是否可以在PHP中将两个相同长度的独立数组合并到一个关联数组中,其中第一个数组的值用作关联数组中的键?

I could ofcourse do this, but I'm looking for another (built-in) function, or more efficient solution..?

我当然可以做到这一点,但我正在寻找另一个(内置)功能,或更有效的解决方案..?

function Combine($array1, $array2) {
    if(count($array1) == count($array2)) {
        $assArray = array();
        for($i=0;$i<count($array1);$i++) {
            $assArray[$array1[$i]] = $array2[$i];
        }
        return $assArray;
    }
}

4 个解决方案

#1


45  

array_combine($keys, $values)

array_combine($ keys,$ values)

PS: Click on my answer! Its also a link!

PS:点击我的回答!它也是一个链接!

#2


7  

you need array_combine.

你需要array_combine。

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

#3


4  

There’s already an array_combine function:

已经有一个array_combine函数:

$combined = array_combine($keys, $values);

#4


2  

hello everybody i will show you how to merge 2 arrays in one array

大家好,我将向您展示如何在一个阵列中合并2个阵列

we have 2 arrays and i will make one array from them

我们有2个数组,我将从它们制作一个数组

 $data_key  = array('key1','key2');
 $data_value = array('val1','val2');

lets declare the main array

让我们声明主数组

$main_array = array();

now let's fill it with the 2 arrays

现在让我们用2个阵列填充它

foreach ($data_key as $i => $key) {
         $main_array[$key] = $data_value[$i];
}

now let's see the result by using var_dump($main_array);

现在让我们通过使用var_dump($ main_array)看到结果;

array(2) { 
["key1"]=> string(4) "val1"
["key2"]=> string(4) "val2" 
}

i hope that can help someone :)

我希望可以帮助别人:)

#1


45  

array_combine($keys, $values)

array_combine($ keys,$ values)

PS: Click on my answer! Its also a link!

PS:点击我的回答!它也是一个链接!

#2


7  

you need array_combine.

你需要array_combine。

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

#3


4  

There’s already an array_combine function:

已经有一个array_combine函数:

$combined = array_combine($keys, $values);

#4


2  

hello everybody i will show you how to merge 2 arrays in one array

大家好,我将向您展示如何在一个阵列中合并2个阵列

we have 2 arrays and i will make one array from them

我们有2个数组,我将从它们制作一个数组

 $data_key  = array('key1','key2');
 $data_value = array('val1','val2');

lets declare the main array

让我们声明主数组

$main_array = array();

now let's fill it with the 2 arrays

现在让我们用2个阵列填充它

foreach ($data_key as $i => $key) {
         $main_array[$key] = $data_value[$i];
}

now let's see the result by using var_dump($main_array);

现在让我们通过使用var_dump($ main_array)看到结果;

array(2) { 
["key1"]=> string(4) "val1"
["key2"]=> string(4) "val2" 
}

i hope that can help someone :)

我希望可以帮助别人:)