2013-10-31 104 views
16

我会给你快速运行我所做的。如果一个或多个数组为空,merge_array返回null?

我使用wordpress和advanced custom fields插件。这是一个基于php的问题,因为这些get_field()字段包含对象数组。

$gallery_location = get_field('gallery_location'); 
$gallery_studio = get_field('gallery_studio'); 

例如$gallery_location倾倒时会返回此...

array(18) { 
    [0]=> 
    array(10) { 
    ["id"]=> 
    int(126) 
    ["alt"]=> 
    string(0) "" 
    ["title"]=> 
    string(33) "CBR1000RR STD Supersport 2014 001" 
    ["caption"]=> 
    string(0) "" 
    ["description"]=> 
    string(0) "" 
    ["mime_type"]=> 
    string(10) "image/jpeg" 
    ["url"]=> 
    string(94) "http://www.example.com/wp/wp-content/uploads/2013/10/CBR1000RR-STD-Supersport-2014-001.jpg" 
    ["width"]=> 
    int(7360) 
    ["height"]=> 
    int(4912) 
    } 
... on so fourth 
} 

然后我使用merge_array合并这两个对象...

$gallery_location = get_field('gallery_location'); 
$gallery_studio = get_field('gallery_studio'); 

$downloads = array_merge($gallery_location, $gallery_studio); 

我合并多个阵列,但如果其中一个数组为空,那么这会导致合并数组完全返回null!

我的问题是如何停止merge_array返回null是一些数组是空的?

在此先感谢您的任何想法。


@zessx

这就是我回来......

$gallery_location = get_field('gallery_location'); 
$gallery_studio  = get_field('gallery_studio'); 

$downloads = array_merge($gallery_location, $gallery_studio); 

var_dump($gallery_location); 

var_dump($gallery_studio); 

var_dump($downloads); 


,这些都是上面相同的顺序堆放的结果...

string(0) "" 


array(18) { 
    [0]=> 
    array(10) { 
    ["id"]=> 
    int(126) 
    ["alt"]=> 
    string(0) "" 
    ["title"]=> 
    string(33) "CBR1000RR STD Supersport 2014 001" 
    ["caption"]=> 
    string(0) "" 
    ["description"]=> 
    string(0) "" 
    ["mime_type"]=> 
    string(10) "image/jpeg" 
    ["url"]=> 
    string(94) "http://www.example.com/wp/wp-content/uploads/2013/10/CBR1000RR-STD-Supersport-2014-001.jpg" 
    ["width"]=> 
    int(7360) 
    ["height"]=> 
    int(4912) 
    } 
... on so fourth 
} 


NULL 


正如你可以看到$downloads仍然返回null,如果我尝试使用下面两个是你的解决方案不起作用?

+0

看起来不错。你有没有尝试过'var_dump($ gallery_location); var_dump($ gallery_studio);'就在'array_merge'之前? – zessx

+0

@zessx - 我刚刚更新了我的问题,这是因为其中一个数组是空的,这会导致合并全部返回null:/ – Joshc

回答

44

array_merge只接受数组作为参数。如果你的参数之一为空,它会引发错误:

警告:array_merge():参数#x是不是数组...

这个错误就不会被上调其中一个数组是空的。一个空数组仍然是一个数组。

两个选项:

1 /强制类型为array

$downloads = array_merge((array)$gallery_location, (array)$gallery_studio); 

2 /检查变量数组

$downloads = array(); 
if(is_array($gallery_location)) 
    $downloads = array_merge($downloads, $gallery_location); 
if(is_array($gallery_studio)) 
    $downloads = array_merge($downloads, $gallery_studio); 

PHP Sandbox

+0

这似乎不会导致null问题,请在底部查看我的问题,已经抛弃了一切,所以你可以看到空数组返回的是什么。感谢您一直以来的帮助。 – Joshc

+0

有一个错字('downlads'而不是'downloads'),但它应该可以工作,[见这个PHP沙箱](http://sandbox.onlinephpfunctions.com/code/7512b59a0e08de604fcb1a87e8ba68d2fb1e57f3) – zessx

+0

我非常爱你现在的作品 - 对不起,我很专注,这是一个便宜的复制和粘贴我的名义。谢谢你帮助男人。 +1 – Joshc

0

您可以使用以下方法合并您的阵列:

$c = (array)$a + (array)$b 
相关问题