简体   繁体   English

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

[英]How to combine two arrays together?

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? 我该怎么办?

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()可能是最简单的解决方案。

You can do this simply with array_combine : 您可以使用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);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM