douweng3383 2018-01-19 10:48
浏览 53
已采纳

如何在具有未知密钥的php中正确打印解码的json

have a json stored in database having unknown keys.

i want to print them like this

array_key : amount for first array key => cigratte_flake, Amount => 2997

here is my decoded json

stdClass Object
(
    [cigratte_flake] => Array
        (
            [0] => stdClass Object
                (
                    [Price] => 999
                    [Quantity] => 3
                    [Amount] => 2997
                )

        )

    [wrestling_board] => Array
        (
            [0] => stdClass Object
                (
                    [Price] => 400
                    [Quantity] => 2
                    [Amount] => 800
                )

        )

    [flex_board_naga_dhaga] => Array
        (
            [0] => stdClass Object
                (
                    [Price] => 300
                    [Quantity] => 2
                    [Amount] => 600
                )

        )

    [total] => Array
        (
            [0] => stdClass Object
                (
                    [Price] => 
                    [Quantity] => 
                    [Amount] => 4397
                )

        )

)

here is my original json:

{"cigratte_flake":[{"Price":"999","Quantity":"3","Amount":"2997"}],"wrestling_board":[{"Price":"400","Quantity":"2","Amount":"800"}],"flex_board_naga_dhaga":[{"Price":"300","Quantity":"2","Amount":"600"}],"total":[{"Price":null,"Quantity":null,"Amount":"4397"}]}

i know this below code, but don't know how to apply in foreach loop, other solution is most appreciated

  reset($a);
  $first_key = key($a);

Please help me thanks in advance!!!

  • 写回答

2条回答 默认 最新

  • dongliang9576 2018-01-19 10:58
    关注

    Just tested this works with your data:

    array_combine(array_keys($array), array_flatten(array_pluck($array, '*.Amount')))
    

    Another approach is to use mapWithKeys() collection method:

    collect($array)->mapWithKeys(function($i, $k) { return [$k => $i[0]['Amount']]; })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥15 抖音看过的视频,缓存在哪个文件