3 回答
TA贡献1862条经验 获得超6个赞
更新PHP 7.2
原始答案(适用于7.2.0之前的版本)
他们从没告诉过你
事实1:
$a = array('123' => '123', '123foo' => '123foo');$o = (object)$a;echo $o->123foo; // error
事实2:
$a = array('123' => '123', '123foo' => '123foo');$o = (object)$a;echo $o->{'123foo'}; // OK!
事实3:
$a = array('123' => '123', '123foo' => '123foo');$o = (object)$a;echo $o->{'123foo'}; // OK!echo $o->{'123'}; // error!
活例.
事实4:
$a = array('123' => '123');$o1 = (object)$a;$o2 = new stdClass;$o2->{'123'} = '123'; // setting property is OKecho $o1->{'123'}; // error!echo $o2->{'123'}; // works... WTF?
活例.
你能做什么
选项1:手动执行
$a = array('123' => '123', '123foo' => '123foo');$o = (object)$a;$a = (array)$o;echo $o->{'123'}; // error!echo $a['123']; // OK!
$highlighting = (array)$myVar->highlighting;$data = (array)$highlighting['448364']->Data;$value = $data['0']; // at last!
备选案文2:核选择
function recursive_cast_to_array($o) { $a = (array)$o; foreach ($a as &$value) { if (is_object($value)) { $value = recursive_cast_to_array($value); } } return $a;}$arr = recursive_cast_to_array($myVar);$value = $arr['highlighting']['448364']['Data']['0'];
选项3:聪明地玩它
$arr = json_decode(json_encode($myVar), true);$value = $arr['highlighting']['448364']['Data']['0'];
json_encode
).
TA贡献1797条经验 获得超6个赞
$arr = array('123' => 'abc');$obj = (object) $arr;$obj->{'123'} = 'abc';print_r( $obj );
stdClass Object ( [123] => 'abc', [123] => 'abc')
#Fact 4
$obj = json_decode(json_encode($arr));
$obj->{123};$obj->{'123'};
TA贡献1839条经验 获得超15个赞
<?php function objectToArray($d) { if (is_object($d)) { // Gets the properties of the given object // with get_object_vars function $d = get_object_vars($d); } if (is_array($d)) { /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return array_map(__FUNCTION__, $d); } else { // Return array return $d; } }?>
首先将数组传递给 objectToArray
功能 然后取返回值 回波 [highlighting][448364][Data][0]
- 3 回答
- 0 关注
- 461 浏览
添加回答
举报