dounieyan2036 2017-08-25 13:05
浏览 512
已采纳

在PHP中删除json数组中的键

I have this

[{"cname":"NCPB"},{"cname":"NBK"}]

Which I'm getting from json_encode

on mysql result

How can I achive this ["NCPB","NBK"] From JSON OBJECT ABOVE.

  • 写回答

1条回答 默认 最新

  • dtn51137 2017-08-25 13:13
    关注

    I guess I can answer this without seeing your exact code. Basically, you're currently fetching your query results with something like this and using json_encode on the result of that:

    while ($row = $query->some_fetch_method()) {
        $results[] = $row;               // you're building an array of associative arrays
    }
    echo json_encode($results);
    

    Instead, just fill the results array with that specific column instead of the entire row.

    while ($row = $query->some_fetch_method()) {
        $results[] = $row['cname'];      // you need to build an array of strings instead
    }
    echo json_encode($results);
    

    You should get the array of query results into the format you want before you use json_encode. Otherwise, you'll have to decode the JSON string you just made, reformat the result of that, and reencode it:

     $json = json_encode(array_column(json_decode($json), 'cname'));
    

    or use some weird regex or something. It doesn't seem to make sense to undo what you've already done, though.

    If you don't get what I mean, edit your question to add the code that fetches your query results, and I'll show you an example based on your exact code, but this should give you the general idea.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率