PHP对象转换数组[duplicate]

时间:2022-03-05 21:33:13

Possible Duplicate:
Casing an Array with Numeric Keys as an Object

可能的重复:用数字键作为对象来封装数组

I made a casting from array to object and I'm confused:

我从数组转换到对象,我很困惑:

$arr = range(1,3);
$obj = (object) $arr;
var_dump($obj)

object(stdClass)#2 (5) {
  [0]=>
    int(1)
  [1]=>
    int(2)
  [2]=>
    int(3)
}

The question is: How to access the object attributes in this case? $obj->0 causes syntax error.

问题是:在这种情况下如何访问对象属性?$ obj - > 0导致语法错误。

3 个解决方案

#1


4  

You can't access these object properties unless you cast back to an array. Period. If you have to do this for some reason, set the array keys to something else.

除非返回到数组,否则无法访问这些对象属性。时期。如果由于某种原因需要这样做,可以将数组键设置为其他类型。

#2


2  

In this case the only thing I can think is to access properties using a foreach like this:

在这种情况下,我唯一能想到的就是使用这样的foreach访问属性:

foreach($obj as $key => $value)
   var_dump("$key => $value");

but of course this won't solve the base problem.

但这当然不能解决基本问题。

#3


1  

It appears that the ArrayObject class can access the properties

ArrayObject类似乎可以访问属性

$a = new ArrayObject($obj);
echo $a[0];

#1


4  

You can't access these object properties unless you cast back to an array. Period. If you have to do this for some reason, set the array keys to something else.

除非返回到数组,否则无法访问这些对象属性。时期。如果由于某种原因需要这样做,可以将数组键设置为其他类型。

#2


2  

In this case the only thing I can think is to access properties using a foreach like this:

在这种情况下,我唯一能想到的就是使用这样的foreach访问属性:

foreach($obj as $key => $value)
   var_dump("$key => $value");

but of course this won't solve the base problem.

但这当然不能解决基本问题。

#3


1  

It appears that the ArrayObject class can access the properties

ArrayObject类似乎可以访问属性

$a = new ArrayObject($obj);
echo $a[0];