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条)

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)