douxian8883 2015-05-05 14:58
浏览 71
已采纳

php获取特定的json数组元素标记

First of all I'm sorry if this is a duplicate question but I couldn't find anything that would work and solve my problem.

I'm fetching data from a DB(Postgres) and parsing that into a Json array. The data looks like this

[{"login":"root@localhost","first_name":"Admin","last_name":"Name","title":null},{"login":"another@localhost","first_name":"More","last_name":"Data","title":"X"}]

My code to fetch this data is something like this:

foreach ($jsonData as $us) {
    $user = new App\User;
    $user->name = $us->login; //same thing for the rest of data

The error I'm getting says that I can't call data from the JSON with -> but var_dump'ing $jsonData states that it's an array with all the correct elements in it.

PS: forgot to add but I tried var_dump($jsonData['login'][0]); to get just the first login (should be "root@localhost") but it says "Undefined index: login"

  • 写回答

1条回答 默认 最新

  • dongzhuohan7085 2015-05-05 15:06
    关注

    Because you JSON is not store in an object, but in a array :

    foreach ($jsonData as $us) {
        $user = new App\User;
        $user->name = $us['login']; //same thing for the rest of data
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀