循环遍历对象属性数组时,如何在给定现有键的情况下返回数组值?

时间:2013-11-28 05:40:48

标签: php arrays object

如果$myObj是:

$myObj = new stdClass();
$myObj = array(1 => 100, 2 => 200, 3 => 300);
echo $myObj[1]; // returns 100, as expected

但是当迭代这样的属性数组时:

$properties_array = array('property_one','property_two');
// and $myObj looks like $myObj->property_one = array(0 => 12345);
foreach ($properties_array as $property) {
    echo $property;
    // returns property name, as expected

    print_r($myObj->$property);
    // returns an array, as expected (ex. Array([0] => 12345))

    echo $myObj->$property[0];
    // expected '12345', instead throws an error: 'Undefined property: stdClass::$myObj'
}

为什么print_r($myObj->$property);会按预期工作,但echo $myObj->$property[0];会抛出错误?

2 个答案:

答案 0 :(得分:2)

尝试echo $myObj->{$property}[0];

答案 1 :(得分:0)

使用键和值概念

  foreach ($properties_array as $key=>$property) {
       echo $property;//100
       echo $key;//1

  }

在回显std类对象时,无法访问对象