如何将两个数组组合在一起?

时间:2022-05-02 08:24:39

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 个解决方案

#1


21  

array_combine() will exactly do what you want.

array_combine()将完全按照你的意愿行事。

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.

使用keys数组中的值作为键创建数组,将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.

当然你也可以使用循环的各种组合来做到这一点,array_combine()可能是最简单的解决方案。

#2


2  

You can do this simply with array_combine:

您只需使用array_combine即可完成此操作:

// First parameter will be used as the keys, the second for the values
$new_array = array_combine($keys_array, $values_array);

#3


1  

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

试试这个:array_combine($ a,$ b);

#1


21  

array_combine() will exactly do what you want.

array_combine()将完全按照你的意愿行事。

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.

使用keys数组中的值作为键创建数组,将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.

当然你也可以使用循环的各种组合来做到这一点,array_combine()可能是最简单的解决方案。

#2


2  

You can do this simply with array_combine:

您只需使用array_combine即可完成此操作:

// First parameter will be used as the keys, the second for the values
$new_array = array_combine($keys_array, $values_array);

#3


1  

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

试试这个:array_combine($ a,$ b);