如何访问已转换为对象的数组的属性/值


How to access the property/ value of an array which has been converted into an object?

如何访问已转换为对象的数组的属性/值?例如,我想访问索引0中的值,

$obj = (object) array('qualitypoint', 'technologies', 'India');
var_dump($obj->0);

错误,

分析错误:语法错误,意外的T_LNUMBER,应为T_STRING或第11行上的C:…conversing_to_object.php中的T_VARIABLE或"{"或"$"

尝试这个:

$obj = (object) array('test' => 'qualitypoint', 'technologies', 'India');
var_dump($obj->test);

结果是:

string(12) "qualitypoint"

但试图访问$obj->0时,出现了相同的错误:Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$'

如果你循环遍历对象,很难,你可以像通常的数组一样正常访问属性:

foreach($obj as $x) {
    var_dump($x);
}

值得注意的是,属性命名规则与基本变量命名规则相同。

如果您将其转换为ArrayObject,则可以正常访问索引:

$obj = new ArrayObject(array('qualitypoint', 'technologies', 'India'));

然后倾倒:

var_dump($obj[0]);

你会得到:

string(12) "qualitypoint"

不能通过$obj->0访问值的原因是它反对PHP变量命名,请参阅http://php.net/manual/en/language.variables.basics.php了解更多信息。即使你使用ArrayObject,你仍然会有同样的问题

但有一个补丁。。。您可以将所有整数键转换为字符串或编写自己的转换函数

示例

$array  = array('qualitypoint', 'technologies', 'India' , array("hello","world"));
$obj = (object) $array;
$obj2 = arrayObject($array);
function arrayObject($array)
{
    $object = new stdClass();
    foreach($array as $key => $value)
    {
        $key = (string) $key ;
        $object->$key = is_array($value) ? arrayObject($value) : $value ;
    }
    return $object ;
}
var_dump($obj2->{0}); // Sample Output
var_dump($obj,$obj2); // Full Output to see the difference 

$sumObject = $obj2->{3} ; /// Get Sub Object
var_dump($sumObject->{1});  // Output world

输出

   string 'qualitypoint' (length=12)

全输出

object(stdClass)[1]
  string 'qualitypoint' (length=12)
  string 'technologies' (length=12)
  string 'India' (length=5)
    array
      0 => string 'hello' (length=5)
      1 => string 'world' (length=5)
object(stdClass)[2]
  public '0' => string 'qualitypoint' (length=12)
  public '1' => string 'technologies' (length=12)
  public '2' => string 'India' (length=5)
  public '3' => 
    object(stdClass)[3]
      public '0' => string 'hello' (length=5)
      public '1' => string 'world' (length=5)

多阵列输出

感谢

:)