警告:array_combine():两个参数应该有相同数量的元素 [英] Warning: array_combine(): Both parameters should have an equal number of elements

查看:57
本文介绍了警告:array_combine():两个参数应该有相同数量的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 array_combine()

中遇到问题<块引用>

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

此错误显示在以下行中:

foreach(array_combine($images, $word) as $imgs => $w){//做点什么}

我该如何解决?

解决方案

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

Array 1: Array (A, B, C)//3个元素数组2:数组(1, 2, 3, 4)//4个元素

array_combine() 不能组合这两个数组,会抛出警告.


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

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

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

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

<块引用>

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

I have a problem here in array_combine()

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

This error gets display on the following line:

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

How can I fix it?

解决方案

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.


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.

这篇关于警告:array_combine():两个参数应该有相同数量的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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