phparraysobject

Isolate a single column of values from an array of objects


This is highly similar to a previous question (Create an array from multidimensional array), yet in this case I do not have a multidimensional array. Here is what I have:

Array
(
    [0] => ratings Object
        (
            [id] => 1
            [rating] => 4.4
        )

    [1] => ratings Object
        (
            [id] => 1
            [rating] => 5.0
        )

    [2] => ratings Object
        (
            [id] => 1
            [rating] => 5.0
        )
)

What I'm attempting to do is create a new array that consists of only the "rating" values...

$result_array = array(0 => "4.4",
                      1 => "5.0",
                      2 => "5.0");

The following solution was unsuccessful since $value is an object rather than an array...

$result_array = array();

foreach ($array as $value) {
    $result_array[] = $value[1];
}

What's the correct way to go about it?


Solution

  • $result_array[] = $value[1];
    

    With the above line, you're trying to use $value as an array when it's not. It's an object, so treat it as such.

    The properties of an object can be accessed using arrow notation (->). The updated code would read:

    foreach ($array as $value) {
        $result_array[] = $value->rating;
    }