Maison > Article > développement back-end > php array读取,该如何解决
php array读取
Array
(
[0] => stdClass Object
(
[userName] => cheng
)
)
Array
(
[0] => stdClass Object
(
[did] => 1
[comment] => Array
(
[user_id] => 4
[userName] => Array
(
[0] => stdClass Object
(
[userName] => cheng
)
)
)
)
如何读取到userName的值
------解决思路----------------------
是不是从json字符串读出来的
json_decode($json_str, true);
这样出来的就不是基类对象了
------解决思路----------------------
1、$ar[0]->userName
2、$ar[0]->comment->userName[0]->userName
如果你是从 json 解码过来的数据,应给 json_decode 的第二个参数赋 true
$ar = json_decode($s, true)
或
$ar = json_decode($s, 1)
这样就全是数组了
1、$ar[0]['userName']
2、$ar[0]['comment']['userName'][0]['userName']
------解决思路----------------------
$array[0]->comment['userName'][0]->userName
------解决思路----------------------
第一个
<br />$obj = new stdClass();<br />$obj->userName = 'cheng';<br />$arr = array($obj);<br /><br />echo $arr[0]->userName;<br />
<br />$obj1 = new stdClass();<br />$obj1->userName = 'cheng';<br /><br />$obj = new stdClass();<br />$obj->did = 1;<br />$obj->comment = array('user_id'=>4,'userName'=>array($obj1));<br /><br />$arr = array($obj);<br />echo $arr[0]->comment['userName'][0]->userName;<br />
<br />$obj1 = new stdClass();<br />$obj1->userName = 'cheng';<br /><br />$obj = new stdClass();<br />$obj->did = 1;<br />$obj->comment = array('user_id'=>4,'userName'=>array($obj1));<br /><br />$arr = array($obj);<br /><br />$result = json_decode(json_encode($arr), true);<br /><br />print_r($result);<br />
<br />Array<br />(<br /> [0] => Array<br /> (<br /> [did] => 1<br /> [comment] => Array<br /> (<br /> [user_id] => 4<br /> [userName] => Array<br /> (<br /> [0] => Array<br /> (<br /> [userName] => cheng<br /> )<br /><br /> )<br /><br /> )<br /><br /> )<br /><br />)<br />