PHP - Merge two arrays (same-length) into one asso

2019-01-12 08:18发布

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?

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条回答
SAY GOODBYE
2楼-- · 2019-01-12 08:59

There’s already an array_combine function:

$combined = array_combine($keys, $values);
查看更多
Ridiculous、
3楼-- · 2019-01-12 09:12

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

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

 $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

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

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

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

i hope that can help someone :)

查看更多
狗以群分
4楼-- · 2019-01-12 09:19

array_combine($keys, $values)

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

查看更多
The star\"
5楼-- · 2019-01-12 09:22

you need array_combine.

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

print_r($c);
?>
查看更多
登录 后发表回答