如何组合两个具有重复值和数组长度差异的数组?

时间:2017-11-29 06:26:45

标签: php arrays

我有两个数组,我希望在结果中有一个数组,并且我想要数组的所有值,即使它们具有相同的值。

我尝试了array_combine(),但是使用重复键是不可能的。

我也试过$array1 + $array2,但这也不是理想的结果。

这些是我的示例输入数组:

$array1 = array(10) { 
    [0]=> string(1) "1" 
    [1]=> string(0) "" 
    [2]=> string(2) "12" 
    [3]=> string(2) "41" 
    [4]=> string(1) "5" 
    [5]=> string(1) "6" 
    [6]=> string(0) "" 
    [7]=> string(2) "11" 
    [8]=> string(2) "23" 
    [9]=> string(2) "10" }

$array2 = array(11) { 
    [0]=> string(1) "A" 
    [1]=> string(1) "B" 
    [2]=> string(1) "C" 
    [3]=> string(1) "D" 
    [4]=> string(1) "E" 
    [5]=> string(1) "F" 
    [6]=> string(1) "G" 
    [7]=> string(1) "H" 
    [8]=> string(1) "I" 
    [9]=> string(2) "J" 
    [10]=> string(1) "K" }

我应该有这样的输出数据:

 $array = array(11){
    [1]=> string(1) "A" 
    []=> string(1) "B" 
    [12]=> string(1) "C" 
    [41]=> string(1) "D" 
    [5]=> string(1) "E" 
    [6]=> string(1) "F" 
    []=> string(1) "G" 
    [11]=> string(1) "H" 
    [23]=> string(1) "I" 
    [10]=> string(2) "J" 
    []=> string(1) "K" }

2 个答案:

答案 0 :(得分:1)

您无法使用array_combine,因为array_combine期望数组的大小相同。事实上,你要求的输出是不可能的。数组键必须是唯一的。你不能拥有

[]=> string(1) "B"
[]=> string(1) "G" 
[]=> string(1) "K"

因为这些会相互覆盖。你最终只得到K.

另一种方法是在每个键有多个值时分配一个数组,例如

[]=> array(3) ["B", "G", "K"]

虽然没有内置功能。您必须手动迭代两个数组并根据需要分配值。一个简单的解决方案是使用MultipleIterator,因为它可以轻松处理不同大小的数组:

$keys = new ArrayIterator(["", 1, "", 2, "", 3]);
$values = new ArrayIterator(["A", "B", "C", "D", "E", "F", "G"]);

$flags = MultipleIterator::MIT_NEED_ANY|MultipleIterator::MIT_KEYS_ASSOC;
$pairs = new MultipleIterator($flags);
$pairs->attachIterator($keys, 'key');
$pairs->attachIterator($values, 'value');

$combined = [];
foreach ($pairs as $pair) {
    $key = $pair['key'];
    $val = $pair['value'];
    if (!isset($combined[$key])) {
        $combined[$key] = $val;
        continue;
    }
    if (!is_array($combined[$key])) {
        $combined[$key] = [$combined[$key]];
    }
    $combined[$key][] = $val;
}

print_r($combined);

然后会产生:

Array
(
    [] => Array
        (
            [0] => A
            [1] => C
            [2] => E
            [3] => G
        )

    [1] => B
    [2] => D
    [3] => F
)

答案 1 :(得分:1)

如果你想组合这两个数组,那么你可以使用$array2的值作为键,因为它们是唯一的(并且它是更长的数组,因此,$array1赢了'被切断了。

$array1=["1","","12","41","5","6","","11","23","10"];
$array2=["A","B","C","D","E","F","G","H","I","J","K"];

foreach($array2 as $i=>$v){
    $result[$v]=(isset($array1[$i])?$array1[$i]:NULL);
}
var_export($result);

输出:

array (
  'A' => '1',
  'B' => '',
  'C' => '12',
  'D' => '41',
  'E' => '5',
  'F' => '6',
  'G' => '',
  'H' => '11',
  'I' => '23',
  'J' => '10',
  'K' => NULL,
)

或者,您可以填充$array1然后合并:

$array1=["1","","12","41","5","6","","11","23","10"];
$array2=["A","B","C","D","E","F","G","H","I","J","K"];
$array1=array_pad($array1,sizeof($array2),NULL);
$result=array_combine($array2,$array1);