Jos*_*shc 23 php arrays advanced-custom-fields
我会快速告诉你我正在做的事情.
我正在使用wordpress与高级自定义字段插件.这是一个基于php的问题,因为这些get_field()
字段包含对象数组.
$gallery_location = get_field('gallery_location');
$gallery_studio = get_field('gallery_studio');
Run Code Online (Sandbox Code Playgroud)
例如,$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
}
Run Code Online (Sandbox Code Playgroud)
然后我使用merge_array合并两个对象......
$gallery_location = get_field('gallery_location');
$gallery_studio = get_field('gallery_studio');
$downloads = array_merge( $gallery_location, $gallery_studio );
Run Code Online (Sandbox Code Playgroud)
我正在合并多个数组但是如果其中一个数组为空,那么这会导致merge数组完全返回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);
Run Code Online (Sandbox Code Playgroud)
以上这些是以相同顺序转储的结果......
string(0) ""
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
NULL
Run Code Online (Sandbox Code Playgroud)
你可以看到$downloads
仍然返回null,如果我尝试使用下面的解决方案,它不起作用?
zes*_*ssx 60
array_merge
仅接受数组作为参数.如果您的某个参数为null,则会引发错误:
警告:array_merge():参数#x不是数组...
如果其中一个数组为空,则不会引发此错误.空数组仍然是一个数组.
两种选择:
1 /强制类型 array
$downloads = array_merge( (array)$gallery_location, (array)$gallery_studio );
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)