【问题标题】:How can I call a function within the foreach loop and avoid redeclaring error如何在 foreach 循环中调用函数并避免重新声明错误
【发布时间】:2015-07-11 17:43:38
【问题描述】:

致命错误:无法重新声明 short_count()(之前在 below-code:22) 在 below-code 第 20 行

<?php
require_once( './wp-blog-header.php' ); 
query_posts('&showposts=-1');

    if(have_posts()) {

        while(have_posts()) : the_post();

            $prmlks = '"'. get_the_permalink(). '",';
            $links = array( $prmlks );
            foreach ($links as $items) {
                $json_data = get_transient( 'cache_'. $id .'_tr' );
                if ($json_data === false) {
                    $id = get_the_ID();
                    $json = file_get_contents( 'http://api.facebook.com/restserver.php?method=links.getStats&format=json&urls=' . $items . '&pretty=1' );
                    $json_data = json_decode($json, true);
                    set_transient( 'cache_'. $id .'_tr', $json_data, 3600 );
                }

                function short_count() {

                    $num = $json_data[0]['total_count'];
                    if(empty ($num) ) {
                        return 'n/a';
                    } else {
                    if( $num < 1000 ) return $num;
                    $x = round($num);
                    $x_number_format = number_format($x);
                    $x_array = explode(',', $x_number_format);
                    $x_parts = array('k', 'm', 'b', 't');
                    $x_count_parts = count($x_array) - 1;
                    $x_display = $x;
                    $x_display = $x_array[0] . ((int) $x_array[1][0] !== 0 ? '.' . $x_array[1][0] : '');
                    $x_display .= $x_parts[$x_count_parts - 1];
                    return  $x_display;
                    }

                }


                $short_count = short_count();
                echo $short_count;

}
        endwhile;

    }

?>

问题是:如何在foreach 循环中调用函数?

我想将函数保留在foreach 循环中,以便获取动态变量..

【问题讨论】:

    标签: php foreach


    【解决方案1】:

    即使您想将函数保留在foreach 循环中,也不是必须的。您可以简单地将函数移到循环之外,只更改以下内容:

    function short_count($data) {
        $num = $data[0]['total_count'];
        ...
    }
    

    foreach循环中你可以简单的调用方法如下:

    $short_count = short_count($json_data);
    

    $json_data 是您在函数中使用的唯一部分,它是在 foreach 循环内创建的,但在 short_count 函数之外。通过将其作为参数传递到您的函数中,您现在可以将其从 foreach 循环中完全删除。

    【讨论】:

      【解决方案2】:

      将您的函数移出循环。你只需要声明一次,而不是多次,所以它不需要在那个循环中。您可以将函数移动到代码顶部(require_once 之后)甚至代码底部(?&gt; 之前),这样就不会遇到此重新声明问题。你可以在循环内部调用任何你想要的函数。

      【讨论】:

      • 非常感谢!我已将其移出循环并将其放在require_once 之后,并且使用$data 可以正常工作。谢谢!!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 2023-03-28
      • 2020-06-15
      相关资源
      最近更新 更多