1

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?

3
  • As there're 3 elements in $array there will be three iterations in a loop. What do you expect? Commented Feb 23, 2014 at 17:17
  • Amal - still don't know. Was waiting on your answer. You answered the original question so I gave you the check mark for that at least Commented Feb 23, 2014 at 18:46
  • Nevermind, very stupid mistake on my part. I was running the print_r within the foreach loop. All is good now. Thanks for the help. Commented Feb 23, 2014 at 18:59

1 Answer 1

1
$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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.