php - How to access object properties with names like integers? -
how access php associative array element output is:
[highlighting] => stdclass object ( [448364] => stdclass object ( [data] => array ( [0] => tax amount liability .......
i want access string value in key [0]. want like:
print myvar->highlighting->448364->data->0
but 2 numerals/integers there seems problem.
edit:
i give bit of history here myvar. using json_decode()
like:
$myvar = json_decode(url)
php has share of dark alleys really don't want find inside. object properties names numbers 1 of them...
what never told you
fact #1: cannot access properties names not legal variable names easily
$a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; echo $o->123foo; // error
fact #2: can access such properties curly brace syntax
$a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; echo $o->{'123foo'}; // ok!
fact #3: not if property name digits!
$a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; echo $o->{'123foo'}; // ok! echo $o->{'123'}; // error!
fact #4: well, unless object didn't come array in first place.
$a = array('123' => '123'); $o1 = (object)$a; $o2 = new stdclass; $o2->{'123'} = '123'; // setting property ok echo $o1->{'123'}; // error! echo $o2->{'123'}; // works... wtf?
pretty intuitive, don't agree?
what can do
option #1: manually
the practical approach cast object interested in array, allow access properties:
$a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; $a = (array)$o; echo $o->{'123'}; // error! echo $a['123']; // ok!
unfortunately, not work recursively. in case 'd need like:
$highlighting = (array)$myvar->highlighting; $data = (array)$highlighting['448364']->data; $value = $data['0']; // @ last!
option #2: nuclear option
an alternative approach write function converts objects arrays recursively:
function recursive_cast_to_array($o) { $a = (array)$o; foreach ($a &$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'];
however, 'm not convinced better option across board because needlessly cast arrays of properties not interested in are.
option #3: playing clever
an alternative of previous option use built-in json functions:
$arr = json_decode(json_encode($myvar), true); $value = $arr['highlighting']['448364']['data']['0'];
the json functions helpfully perform recursive conversion array without need define external functions. desirable looks, has "nuke" disadvantage of option #2 and additionally disadvantage if there strings inside object, strings must encoded in utf-8 (this requirement of json_encode
).
Comments
Post a Comment