PHP循环遍历stdClass对象的数组

时间:2014-05-01 15:50:23

标签: php arrays stdclass

我有一个在MySQL中运行的查询,它将结果作为stdClass对象返回如下:

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"
  }
}

我想获得颜色值。如何遍历此对象并将每个十六进制颜色存储在数组中?

2 个答案:

答案 0 :(得分:6)

够容易。遍历数组并访问对象和color属性并将其分配给新的数组元素:

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

答案 1 :(得分:1)

您应该能够使用foreach循环并遍历数组。由于每个数组元素都是一个对象,你可以这样做:

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