How to combine two arrays together?

2019-01-02 21:26发布

Is there a quick way to combine one arrays values as the other array's keys?

Input:

array A => Array (
        [0] => "cat"
        [1] => "bat"
        [2] => "hat"
        [3] => "mat"
    )

array B => Array (
        [0] => "fur"
        [1] => "ball"
        [2] => "clothes"
        [3] => "home"
    )

Expected output:

array C => Array (
        [cat] => "fur"
        [bat] => "ball"
        [hat] => "clothes"
        [mat] => "home"
    )

How could I do that?

3条回答
冷夜・残月
2楼-- · 2019-01-02 21:52

You can do this simply with array_combine:

// First parameter will be used as the keys, the second for the values
$new_array = array_combine($keys_array, $values_array);
查看更多
还给你的自由
3楼-- · 2019-01-02 21:58

Try this: array_combine($a, $b);

查看更多
不流泪的眼
4楼-- · 2019-01-02 22:06

array_combine() will exactly do what you want.

Quoting the manual:

array array_combine ( array $keys , array $values )

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

In your case, you'd have to do something like this:

$array['C'] = array_combine($array['A'], $array['B']);

While of course you could also use various combinations of loops to do that, array_combine() is probably the simplest solution.

查看更多
登录 后发表回答