如何两个数组结合起来? [英] How to combine two arrays together?

查看:275
本文介绍了如何两个数组结合起来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个快速的方式给一个数组的值作为组合的另一阵列的钥匙?

输入:

 数组A =>阵列(
        [0] => 猫
        [1] => 蝙蝠
        [2] => 帽子
        [3] => 垫
    )数组B =>阵列(
        [0] => 毛皮
        [1] => 球
        [2] => 衣服
        [3] => 家
    )

期望的输出:

 阵列C =>阵列(
        [猫] => 毛皮
        [蝙蝠] => 球
        [帽子] => 衣服
        [垫子] => 家
    )

我怎么能这样做?


解决方案

<强> array_combine() 会正是你想要做什么。

引述手册:


 阵列array_combine(数组$键,数组$值)


  
  

通过使用来自值数组作为相应的值,从键阵列作为键的值和值创建一个数组


在你的情况,你必须做这样的事情:

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


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

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.

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.

这篇关于如何两个数组结合起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆