PHP合并2阵列成一个关联数组 [英] php merge 2 arrays into one associative array

查看:266
本文介绍了PHP合并2阵列成一个关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP,我需要2个数组合并(长度相等为一个关联数组),这里是从我的当前数据集的摘录:

Using PHP I need to merge 2 arrays (of equal length into one associative array) here is an excerpt from my current data set:

[1] => Array
    (
        [0] => C28
        [1] => C29
    )

[2] => Array
    (
        [0] => 1AB010050093
        [1] => 1AB008140029
    )

这两个元素[1] [2]实际上很多不仅仅是2子元素更长(就像我说的,这是一个节选)。

both elements [1] and [2] are actually a lot longer than just 2 sub-elements (like I said, this is an excerpt).

该协议是,C28在第一阵列中对应于1AB010050093第二阵列,等等...我需要的结果是创建一个新的关联数组,看起来像这样:

The deal is that "C28" in the first array corresponds to "1AB010050093" in the second array, and so on... The result I need is to create a new associative array that looks like this:

[1] => Array    
    (
        ['ref']  => C28
        ['part'] => 1AB010050093
    )
[2] => Array
    (
        ['ref'] => C29
        ['part'] => 1AB008140029
    )

等等...

推荐答案

如果你愿意与一个数组结构,这样的妥协:

If you are willing to compromise with an array structure like this:

array(
    'C28' => '1AB010050093',
    'C29' => '1AB008140029'
);

然后就可以使用 array_combine() codePAD演示):

array_combine($refNumbers, $partIds);

否则,你需要使用foreach( codePAD演示):

$combined = array();

foreach($refNumbers as $index => $refNumber) {
    if(!array_key_exists($index, $partIds)) {
        throw OutOfBoundsException();
    }

    $combined[] = array(
        'ref'  => $refNumber,
        'part' => $partIds[$index]
    );
}

这篇关于PHP合并2阵列成一个关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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