【问题标题】:Warning: Invalid argument supplied for foreach() php [duplicate]警告:为 foreach() php 提供的参数无效 [重复]
【发布时间】:2012-11-13 02:54:28
【问题描述】:

我在第 5 行收到此警告,警告:foreach() 提供的参数无效

if (!function_exists('get_user_online_count')) {
    function get_user_online_count($type=false,$full=true) {
        global $counter_matrix;
        $user_types=array();
        foreach($counter_matrix as $key=>$val){
            if(!isset($user_types[$val['user_type']])){
                $user_types[$val['user_type']] = 0;
            }
            $user_types[$val['user_type']] ++;
        }
        if($full){
            $print = '';
            while(count($user_types)){
                $user_type = key($user_types);
                $user_count = array_shift($user_types);
                if($type && $user_type != $type)continue;
                if($print!=''){
                    if(count($user_types))$print .= ', ';
                    else $print .= ' and ';
                }else{

                }
                $print .= $user_count . ' ' . $user_type . (($user_count>1)?'s':'');
            }
            if(!$print){
                if($type){
                    $print = '0 '.$type.'s online';
                }else{
                    $print = '0 Users online';
                }
            }else{
                $print .= ' online';
            }
            return $print;
        }else{
            if($type){
                return (isset($user_types[$type])) ? $user_types[$type] : 0;
            }else{
                return count($counter_matrix);
            }
        }
    }
}

我在这一行有警告'foreach($counter_matrix as $key=>$val){'

这里怎么了???

【问题讨论】:

  • 好像$counter_matrix不是数组

标签: php


【解决方案1】:

原因是你的全局变量$counter_matrix 不是数组。

您可以检查将其放在您的 foreach 之前:

echo gettype($counter_matrix);

这会告诉你变量的类型,或者你也可以使用var_dump($counter_matrix),它也会打印内容。

【讨论】:

  • echo gettype($counter_matrix);结果为空
  • 这意味着您没有全局 $counter_matrix 变量,请检查变量名称中的拼写错误,查看该变量的创建位置,确保它在全局范围内(不在任何函数内)。
猜你喜欢
  • 2014-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-01
相关资源
最近更新 更多