使用魔法字段时如何检查数组

时间:2013-03-04 03:39:34

标签: php arrays wordpress

我尝试使用下面的代码检查数组是否存在,问题是当getFieldOrder('image_gal')内没有图像时它会返回此错误。

错误输出

Warning: array_reverse() [function.array-reverse]: The argument should be an array in /home/sritamac/public_html/wp-content/plugins/magic-fields/get-custom.php on line 306

Warning: sort() expects parameter 1 to be array, null given in /home/sritamac/public_html/wp-content/plugins/magic-fields/get-custom.php on line 307

数组代码:

<?php
//var
$images = getFieldOrder('image_gal');

if (is_array($images)) {

    foreach ($images as $image) {

        if (get('image_gal', 1, $image) == TRUE) { //check if image_gallery_image has image 
?> 

    <div id="wrap">
        <ul id="mycarousel" class="jcarousel-skin-tango">
            <?php
            $images = getFieldOrder('image_gal');
            foreach ($images as $image) { //loop image 
            ?>
            <li>
                <a class="group3"  href="<?php echo get('image_gal', 1, $image);?>">
                    <img src="<?php echo get('image_gal', 1, $image);?>" width="150" height="150" alt="" />
                </a>
            </li>  
            <?php
            }
            ?>  
        </ul>
    </div>
<?php
            break;
        }
    }
}
?>

我使用这个主题http://www.s5themes.com/theme/webfolio/而wordpress版本是3.2.1。

Magic Fields插件http://magicfields.org/

1 个答案:

答案 0 :(得分:0)

此问题是因为,在array_reverse()sort()中,您传递的是非数组变量。

解决方案:

  1. 检查参数,在执行这些功能之前,执行这些参数 仅当参数是数组时才起作用。你可以使用is_array 功能

    if(is_array($array)){
        sort($array);
    }
    
  2. 检查您的参数,如果它为null或非数组使其成为数组。在将其传递给函数之前。

    if(!is_array($array) || $array = "" || $array = NULL){
        $array = array();
    }
    sort($array);
    
  3. 我建议您使用第二种解决方案,因为即使数组为空,也不会影响其他功能。