在php中组合具有相同键的两个数组 [英] combine two arrays with the same key in php

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

问题描述

您好,您是 php 的新手,非常需要您的帮助.我实际上有两个数组,我希望它组合起来.

Hello Just a newbie in php and need your help badly. I actually have two array and I want it to to combine.

    ['a1']=>array(
    [0]=>200,
    [1]=>300,
    [2]=>300
    ),

    ['a2']=>array(
    [0]=>100,
    [1]=>600,
    [2]=>200
    )

    ['a1']=>array(
    [0]=>gen,
    [1]=>gen2,
    [2]=>gen
       ),
    ['a2']=>array(
    [0]=>gen2,
    [1]=>gen3,
    [2]=>gen3
       )

我希望我的输出是:

[a1]=>(
         [gen]=>200,
         [gen2]=>300,
         [gen]=>300,
        )
  [a2]=>(
         [gen2]=>100,
         [gen3]=>600,
         [gen3]=>200,
        )

非常感谢您的帮助

我尝试了这段代码并且能够得到我想要的结果,除非有重复,它不显示重复的值,或者如果键是重复的,如果有选择,它必须添加值.

I try this code and able to get my desire result except when there is a duplicate, it doesn't show the duplicate value or if have choice if the key is duplicate, it must add the value.

再次感谢您的帮助.

<?php
$array1 = array(a1=>array(200,300,300), a2=>array(100,600,200));
$array2 = array(a1=>array('gen','gen2','gen'), a2=>array('gen2','gen3','gen3'));
$result = array();
foreach($array1 as $k => $v) {
$result[$k] = array_combine($array2[$k], $v);
}

print_r($result);
?>

推荐答案

使用 <代码>array_combine():

$keys = array(0=>'gen', 1=>'gen2', 2=>'gen3');
$values = array(0=>200, 1=>300, 2=>300);
$a1 = array_combine($keys, $values);

注意:我根据您提供的 print_r() 输出重建了您的数组.但这应该会让你开始.

Note: I rebuilt your arrays as you provided the print_r() output. But this should get you started.

这篇关于在php中组合具有相同键的两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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