Cortez Ninja
Cortez Ninja

Reputation: 89

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

I need a help on below, I know its raised in a past but I am currently struggling to figure it out the error Cannot use object of type stdClass as array on line

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

Code:

<?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();

  ?>

Upvotes: 0

Views: 6675

Answers (2)

Ryan
Ryan

Reputation: 28177

Take a look at how you declared $score.

First you do $scorex=array($row_cnt); and then $score=(object)$scorex;.

So $score is cast to an object. However, in your code, you are still addressing it like an array, i.e. $score[$counter]. You should reference it as an object.

EDIT

Alternatively, update your definition for $score to the following:

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

This way, your assignment to $score[$counter] will still work (i think in the way you intended).

Upvotes: 1

zerkms
zerkms

Reputation: 254886

mysqli_fetch_object returns an object.

So after the line $row=mysqli_fetch_object($result) is an object.

If you want an array use mysqli_fetch_array instead.

And before using that array check its contents with var_dump($row); (to prevent further questions).

Upvotes: 2

Related Questions