>  기사  >  백엔드 개발  >  php array读取,该如何解决

php array读取,该如何解决

WBOY
WBOY원래의
2016-06-13 12:11:241102검색

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 />

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.