2

I am using a PHP framework CodeIgniter to throw together a quick project. I am running into a PHP related issue with one of my loops/arrays and I am looking for a push in the right direction.

PHP Database Call:

public function get_feed_data()
    {
            $query = $this->db->query('SELECT c.id, c.name, c.age, c.photoName, c.photoNameSmall, c.panelColor , IFNULL(SUM(t.points), '.MAX_POINTS.') as totalPoints
                                    FROM children as c 
                                    LEFT JOIN behaviorRatings as r
                                    ON c.id = r.childID
                                    LEFT JOIN behaviorTypes as t
                                    ON r.behaviorID = t.behaviorTypeID
                                    GROUP BY c.id');
            return $query->result();
    }

My Controller:

    $feedData   =   $this->display_model->get_feed_data();
    $output = array();

    foreach($feedData as $d)
    {
        $rating = $this->_current_behavior($d->totalPoints[0]);
        $d['rating'] = $rating;
        $output[] = $d;
    }

    $response              = array();
    $response['timestamp'] = $currentmodif;
    $response['children']  = $output;
    echo json_encode($response);

The Issue:

The database call returns multiple records of data from the tables without any issues. However, I am trying to add another key/value pair to that array that is calculated through another function.

In the array, I am trying to add the key rating with the value of $rating.

The error I am getting is Cannot use object of type stdClass as array. I assumed that $feedData was an array that I could have just pushed this value into but that doesn't seem to be the case.

Any thoughts?

2
  • change $d['rating'] = $rating; to $d->rating = $rating. as the error suggests, the array $feedData actually a bunch of stdClass not another array, so you only need to use it as object. luckily, php is such a nice language, it lets you to add object properties on a whim. Commented Dec 30, 2016 at 1:34
  • @SBB did you check the answer? Commented Dec 30, 2016 at 19:48

1 Answer 1

7

Your problem is that probably the $d variable is stdClass (and not Array) and therefore you can't use $d[..] on that object, because this syntax is for Array access, and not Objects.

The syntax to access Object's members is ->:

$d->rating = $rating;

So your complete loop will look like:

foreach($feedData as $d)
{
    $rating = $this->_current_behavior($d->totalPoints[0]);
    $d->rating = $rating;
    $output[] = $d;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.