php 警告:array_combine():两个参数应该有相同数量的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19394980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:24:27  来源:igfitidea点击:

Warning: array_combine(): Both parameters should have an equal number of elements

phparrays

提问by Atashi Dubz

I have a problem here in array_combine()

我这里有问题 array_combine()

Warning: array_combine(): Both parameters should have an equal number of elements in PATH on line X

警告:array_combine():这两个参数在 X 行的 PATH 中应该具有相同数量的元素

This error gets display on the following line:

此错误显示在以下行中:

foreach(array_combine($images, $word) as $imgs => $w)
{
    //do something
}

How can I fix it?

我该如何解决?

回答by Anand Solanki

This error appears when you try to combine two arrays with unequal length. As an example:

当您尝试组合两个长度不等的数组时,会出现此错误。举个例子:

Array 1: Array (A, B, C)     //3 elements
Array 2: Array (1, 2, 3, 4)  //4 elements

array_combine()can't combine those two arrays and will throw a warning.

array_combine()不能组合这两个数组并会发出警告。



There are different ways to approach this error.

有多种方法可以解决此错误。

You can check if both arrays have the same amount of elements and only combine them if they do:

您可以检查两个数组是否具有相同数量的元素,并且只有在它们存在时才将它们组合起来:

<?php

    $arrayOne = Array("A", "B", "C");
    $arrayTwo = Array(1, 2, 3);

    if(count($arrayOne) == count($arrayTwo)){
        $result = array_combine($arrayOne, $arrayTwo);
    } else{
        echo "The arrays have unequal length";
    }

?>

You can combine the two arrays and only use as many elements as the smaller one has:

您可以组合两个数组,并且只使用与较小数组一样多的元素:

<?php

    $arrayOne = Array("A", "B", "C");
    $arrayTwo = Array(1, 2, 3);

    $min = min(count($arrayOne), count($arrayTwo));
    $result = array_combine(array_slice($arrayOne, 0, $min), array_slice($arrayTwo, 0, $min));

?>

Or you can also just fill the missing elements up:

或者你也可以只填充缺失的元素:

<?php

    $arrayOne = Array("A", "B", "C");
    $arrayTwo = Array(1, 2, 3);

    $result = [];
    $counter = 0;

    array_map(function($v1, $v2)use(&$result, &$counter){
        $result[!is_null($v1) ? $v1 : "filler" . $counter++] = !is_null($v2) ? $v2 : "filler";     
    }, $arrayOne, $arrayTwo);

?>

Note:That in all examples you always want to make sure the keys array has only unique elements! Because otherwise PHP will just overwrite the elements with the same key and you will only keep the last one.

注意:在所有示例中,您始终希望确保键数组只有唯一元素!因为否则 PHP 只会覆盖具有相同键的元素,您将只保留最后一个。