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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1200885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:30:11  来源:igfitidea点击:

PHP - Merge two arrays (same-length) into one associative?

phparraysmergeassociative-array

提问by Ropstah

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;
    }
}

回答by Tyler Carter

array_combine($keys, $values)

array_combine($keys, $values)

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

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

回答by OneOfOne

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);
?>

回答by Gumbo

There's already an array_combinefunction:

已经有一个array_combine功能

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

回答by elaz

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 :)

我希望可以帮助某人:)