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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用