简体   繁体   English

PHP array_merge如果不为空

[英]PHP array_merge if not empty

Trying to merge 4 arrays, but some may be empty at certain times. 尝试合并4个数组,但某些数组在某些时候可能为空。

$array_1 = array('something1', something2);
$array_2 = array('something3', something4);
$array_3 = array();
$array_4 = array('something1', something2);

$list = array_merge($array_1,$array_2,$array_3,$array_4);

print_r($list);

But if one of the arrays are empty, there will be an error. 但是,如果其中一个数组为空,则会出现错误。 I've been googling forever, but I can't find a solid simple answer on how to check for empty arrays before merging. 我一直在谷歌搜索,但是我找不到关于合并前如何检查空数组的可靠简单答案。

Argument #2 is not an array 参数2不是数组

Or whichever array is empty is the argument number. 或者,无论哪个数组为空都是参数编号。 How do I strip out empty arrays before merging? 合并前如何去除空数组?

There is NO error with an empty array. 空数组没有错误。 There is only an error if the arg is NOT an array. 如果arg不是数组,则只有一个错误。

You could check is_array() or: 您可以检查is_array()或:

$list = array_merge(
(array)$array_1,
(array)$array_2,
(array)$array_3,
(array)$array_4
);

Okay here you go, this should do the trick (if you make array of the initial arrays): 好的,到这里,这应该可以解决问题(如果您将初始数组作为数组):

$arrs = array();

$arrs[] = array('something1', something2);
$arrs[] = array('something3', something4);
$arrs[] = array();
$arrs[] = array('something1', something2);

$list = array();

foreach($arrs as $arr) {
    if(is_array($arr)) {
        $list = array_merge($list, $arr);
    }
}

print_r($list);

Array merge supports empty array() 数组合并支持空array()

Doc: 文件:

Example #3 Simple array_merge() example http://us1.php.net/array_merge Example#3简单的array_merge()示例http://us1.php.net/array_merge

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

Result
Array
(
    [0] => data
)

You are getting notice because something2, something4 should be quoted as string or $ as variable. 您会注意到,因为something2,something 4应该用字符串或$作为变量引用。

PHP Notice:  Use of undefined constant something2 - assumed 'something2' 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM