繁体   English   中英

PHP致命错误:无法将stdClass类型的对象用作数组

[英]PHP Fatal error: Cannot use object of type stdClass as array

我在下面需要帮助,我知道它在过去曾提出过,但是我目前正在努力找出错误无法将stdClass类型的对象用作在线数组

$score[$counter] = ($bronze * $tempArray[6]) + ($silver * $tempArray[5]) + ($silver * $tempArray[4]);

码:

<?php
       //turning the date other way around that is why explode the date string and stored in an Array
    $gold=$_GET['gold_input'];
    $silver=$_GET['silver_input'];
    $bronze=$_GET['bronze_input'];
    $gdp_value=$_GET['gdp_checked'];
    $link = new mysqli('localhost', 'root', '','coa123cdb');
    $myArray = array();
    //data format for information
//[{"name":"Ahmet Akdilek","country_name":"Turkey","gdp":"773091000000","population":"72752000"}
    $query = "SELECT  * FROM  coa123cdb.Country";

    $result = mysqli_query($link, $query)
    or die("Error: ".mysqli_error($link));
    $row_cnt = $result->num_rows;
    if ($result = $link->query($query)) {
    $tempArray = array();
    $scorex=array($row_cnt);
    $score=(object)$scorex;
    $counter=0  ;
    //while($row = $result->fetch_object()) {
    while($row=mysqli_fetch_object($result)){

      $tempArray = $row;
                if($gdp_value==0)
            {
            $score[$counter]=($bronze*$tempArray[6])+($silver*$tempArray[5])+($silver*$tempArray[4]);
            }
            else
            {$score[$counter]=($bronze*$tempArray[6]+$silver*$tempArray[5]+$silver*$tempArray[4])*$tempArray[1]/$tempArray[2]/10000;
            }
            array_push($tempArray, $score[$counter]);
            array_push($myArray, $tempArray);
                            $counter=$counter+1;
        }



        //var_dump($score);
    echo json_encode($myArray);
    }

    $result->close();
    $link->close();

  ?>

mysqli_fetch_object返回一个对象。

因此,在$row=mysqli_fetch_object($result)之后是一个对象。

如果要使用数组,请使用mysqli_fetch_array代替。

在使用该数组之前,请使用var_dump($row);检查其内容var_dump($row); (以防止出现其他问题)。

看一下如何声明$score

首先,您需要执行$scorex=array($row_cnt); 然后$score=(object)$scorex;

因此$score被强制转换为对象。 但是,在您的代码中,您仍然像数组一样寻址它,即$score[$counter] 您应该将其作为对象引用。

编辑

或者,将$score的定义更新为以下内容:

 $score = array_fill (0, $row_cnt, 0);

这样,您对$score[$counter]分配仍然有效(我认为是您想要的方式)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM