PHP loop through an array of stdClass object

I have a query that I run in MySQL and return the result as an object stdClassas follows:

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 color values. How can I skip this object and get each hex color to store in an array?

+4
source share
2 answers

Simple enough. Scroll through the array and access the object and color property and assign it to the new array element:

foreach($array as $object) {
    $colors[] = $object->color;
}
+6
source

You should be able to use loop foreachand iterate over the array. Since each element of the array is an object, you can do this as follows:

$array = //results from query    
foreach($array as $obj) {
    echo $obj->color;
}
+1
source

Source: https://habr.com/ru/post/1538874/


All Articles