为什么这些代码显示不支持的操作数类型和其他错误?

时间:2016-10-07 19:01:07

标签: php

我是初学者。为什么以下代码显示三个错误?:

  

1)警告:array_keys()期望参数1为数组,在第851行的C:\ wamp \ www \ wordpress \ wp-content \ themes \ testtheme \ functions.php中给出整数

     

2)警告:在851行的C:\ wamp \ www \ wordpress \ wp-content \ themes \ testtheme \ functions.php中为foreach()提供的参数无效   851行:

foreach (array_keys($team_points + $team_points2) as $key) {
    $total_points_final[$key] = (isset($team_points[$key]) ? $team_points[$key] : 0) + (isset($team_points2[$key]) ? $team_points2[$key] : 0);
}
  

3)致命错误:第859行的C:\ wamp \ www \ wordpress \ wp-content \ themes \ testtheme \ functions.php中不支持的操作数类型   859行:

foreach (array_keys($total_points_final + $team_points3) as $key) {
    $total_points_final2[$key] = (isset($total_points_final[$key]) ? $total_points_final[$key] : 0) + (isset($team_points3[$key]) ? $team_points3[$key] : 0);
}

所有代码:

$total_points=0;
    $team_points;
    $team_points2;
    $team_points3;
    foreach($team_wins as $tw_key=>$tw_val){
        $team_points[$tw_key]=$tw_val*3;
    }

    foreach($team_drawn as $tw_key=>$tw_val){
        $team_points2[$tw_key]=$tw_val*1;
    }

    $total_points_final = array();
    $total_points_final2 = array();
    foreach (array_keys($team_points + $team_points2) as $key) {
        $total_points_final[$key] = (isset($team_points[$key]) ? $team_points[$key] : 0) + (isset($team_points2[$key]) ? $team_points2[$key] : 0);
    }

    foreach($team_loses as $tw_key=>$tw_val){
        $team_points3[$tw_key]=$tw_val*0;
    }

    foreach (array_keys($total_points_final + $team_points3) as $key) {
        $total_points_final2[$key] = (isset($total_points_final[$key]) ? $total_points_final[$key] : 0) + (isset($team_points3[$key]) ? $team_points3[$key] : 0);
    } 

2 个答案:

答案 0 :(得分:0)

你只能提供 array_keys()一个有效的数组,它会返回作为参数传递给它的数组的键。

除了任何变量类型之外,它永远不会 您可以像这样创建一个新的空数组:

$arr = [];

然后将这些值添加到空数组中,如下所示:

$arr[] = $post_id;
$arr[] = $post_total;

现在您可以在 array_keys($ arr)中调用新数组

答案 1 :(得分:0)

1. array_keys() => The array_keys() function takes only array  parameter, you cannot pass integer or string.  
example:
$array = array("name"=>"xyz", "email"=>"xxxxxxx@xxxx.xxx");
array_keys($array); //Valid
array_keys(2);//Invalid/Error

2. foreach
  foreach is a looping statement, you cannot pass inetger or string to loop it, 
  pass array to foreach, you cannot pass empty array to foreach,
  check empty condition before passing to foreach

  example:
  foreach($array as $key=>$value) { //valid input for foreach
        echo $value;
  }