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

报告相同问题?