5

I have a query that I run in MySQL and it returns a result as an stdClass object as following :

array(8){
  [
    0
  ]=>object(stdClass)#36(1){
    [
      "color"
    ]=>string(7)"#a0a0a0"
  }[
    1
  ]=>object(stdClass)#35(1){
    [
      "color"
    ]=>string(7)"#e0e0e0"
  }[
    2
  ]=>object(stdClass)#30(1){
    [
      "color"
    ]=>string(7)"#f0f0f0"
  }[
    3
  ]=>object(stdClass)#37(1){
    [
      "color"
    ]=>string(7)"#f0f0f1"
  }[
    4
  ]=>object(stdClass)#34(1){
    [
      "color"
    ]=>string(7)"#404040"
  }[
    5
  ]=>object(stdClass)#38(1){
    [
      "color"
    ]=>string(7)"#c0c0c0"
  }[
    6
  ]=>object(stdClass)#39(1){
    [
      "color"
    ]=>string(7)"#e06080"
  }[
    7
  ]=>object(stdClass)#40(1){
    [
      "color"
    ]=>string(7)"#e06082"
  }
}

I would like to get the colors values. How can I loop through this object and get each hex color to store in an array?

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
user3593154
  • 115
  • 2
  • 9
  • possible duplicate of [stdClass object and foreach loops](http://stackoverflow.com/questions/950827/stdclass-object-and-foreach-loops) – Jamie Taylor May 01 '14 at 15:52
  • 2
    `foreach ($array as $obj) { echo $obj->color; }` – Amal Murali May 01 '14 at 15:52
  • @JamieTaylor That question bears no resemblance to this one and the solutions won't help. – Michael Berkowski May 01 '14 at 15:53
  • @MichaelBerkowski How so? they both seem to be similar to me. The most upvoted answer explains the foreach loop within stdClass objects well too. Apologies for my confusion. – Jamie Taylor May 01 '14 at 15:54
  • Why put your data into that data array of objects structure at all? I think I would just query the data and load values your are interested in into a numerically indexed array from the start. – Mike Brant May 01 '14 at 15:54
  • 1
    @JamieTaylor This requires a loop on the outer array. It's really just a matter of the OP not understanding the data structure. – Michael Berkowski May 01 '14 at 15:57
  • @MichaelBerkowski I suppose, I would argue it's still quite a similar solution. – Jamie Taylor May 01 '14 at 16:00

2 Answers2

7

Easy enough. Loop through the array and access the object and the color property and assign it to a new array element:

foreach($array as $object) {
    $colors[] = $object->color;
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
1

You should be able to use a foreach loop and iterate through the array. Since each array element is an object you can do it like so:

$array = //results from query    
foreach($array as $obj) {
    echo $obj->color;
}
miriye
  • 143
  • 5