当前位置:Gxlcms > PHP教程 > phparray读取,该如何解决

phparray读取,该如何解决

时间:2021-07-01 10:21:17 帮助过:11人阅读

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
------解决思路----------------------
第一个

$obj = new stdClass();
$obj->userName = 'cheng';
$arr = array($obj);

echo $arr[0]->userName;


第二个

$obj1 = new stdClass();
$obj1->userName = 'cheng';

$obj = new stdClass();
$obj->did = 1;
$obj->comment = array('user_id'=>4,'userName'=>array($obj1));

$arr = array($obj);
echo $arr[0]->comment['userName'][0]->userName;


如果简单点可以全部变数组

$obj1 = new stdClass();
$obj1->userName = 'cheng';

$obj = new stdClass();
$obj->did = 1;
$obj->comment = array('user_id'=>4,'userName'=>array($obj1));

$arr = array($obj);

$result = json_decode(json_encode($arr), true);

print_r($result);


Array
(
[0] => Array
(
[did] => 1
[comment] => Array
(
[user_id] => 4
[userName] => Array
(
[0] => Array
(
[userName] => cheng
)

)

)

)

)

人气教程排行