【问题标题】:PHP return array as NULL after foreach [closed]PHP在foreach之后将数组返回为NULL [关闭]
【发布时间】:2014-09-21 01:44:28
【问题描述】:

我不知道为什么我的函数总是返回 NULL。 return 之前的 var_dump($args) 显示 $args 中的项目太多。但是当我在另一个地方调用这个函数时,它返回 NULL。有人能帮我吗?谢谢。

在评论中我解释了情况。

function LBE_result_hompage_search_ecole_map()
{
    //  Get department code when user click map
    $code = $_POST['code'];
    // Query data from database
    global $wpdb;
    $table_name = $wpdb->prefix.'utils_ville';
    $query = "SELECT nom_ville,code_postal FROM ".$table_name." WHERE departement=%d";
    $results = $wpdb->get_results( $wpdb->prepare($query, $code) );

    $args = array();

    foreach($results as $result):
        $arg = array(
            'posts_per_page'   => 10,
            'orderby'          => 'post_date',
            'order'            => 'DESC',
            'post_type'        => 'ecole',
            'post_status'      => 'publish',
            'meta_query'       => array(
            'relation' => 'AND',
                array(
                    'key' => 'ecole_ville',
                    'value' => $result->nom_ville,
                    'compare' => '='
                ),
                array(
                    'key' => 'ecole_post',
                    'value' => $result->code_postal,
                    'compare' => '='
                )
            )
        );
        $args[] = $arg;
    endforeach;
    var_dump($args);  // Here shows so many items in $args
    return($agrs);
}
$args = LBE_result_hompage_search_ecole_map();
var_dump($args);  // Here shows NULL. I don't know why...

【问题讨论】:

  • 你的函数中有 argsagrs
  • 非常感谢。我很抱歉,甚至不能原谅我这种低级的错误。我认为优秀的开发人员从小事做起。

标签: php arrays foreach null return


【解决方案1】:

return 不是函数。另外,你放的是 agrs 而不是 args。

return($agrs); 更改为return $args;

"Note: Note that since return is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case."

http://php.net/manual/en/function.return.php

【讨论】:

  • return 顺便可以当函数使用
  • 不应该,是的,但它是(或可以用作)一个函数
  • 谢谢你,尼古拉斯。你纠正了我的错误并教会了我更多。非常感谢,真的。
【解决方案2】:

您的退货声明中有错字。

return($agrs); 应该是return($args);

【讨论】:

  • 非常感谢。我很抱歉,甚至不能原谅我这种低级的错误。我认为优秀的开发人员从小事做起。
  • @Newbeeee 不用担心。有时,您需要外部眼睛来发现此类错误。
猜你喜欢
  • 2016-07-18
  • 1970-01-01
  • 2018-05-27
  • 1970-01-01
  • 2012-10-04
  • 1970-01-01
  • 2017-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多