【问题标题】:how to print decoded json correctly in php having unknown key如何在具有未知密钥的php中正确打印解码的json
【发布时间】:2018-06-28 14:11:23
【问题描述】:

有一个 json 存储在 数据库 中,而 keys 是未知的。

我想像这样打印它们

array_key : amount 用于第一个数组 key => cigratte_flake, Amount => 2997

这是我解码的 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
                )

        )

)

这是我的原始 json:

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

我知道下面的代码,但不知道如何在 foreach 循环中应用,其他解决方案最赞赏

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

请帮助我提前谢谢!!!

【问题讨论】:

  • 请提供您当前的用于解码和解释 JSON 的 PHP 代码,以便我们了解您遇到的问题 :-)
  • @PhilippMaurer, array key 将是未知的,但它的 values 将是 Price,Quantity,Price
  • 这是我的代码$d = \DB::select('SELECT sqd.quotation_data,pi.* FROM sent_quotation_data sqd INNER JOIN performa_invoice pi on sqd.customer_id = pi.customer_id'); $d = collect($d); $j = json_decode($d[0]->quotation_data);

标签: php laravel


【解决方案1】:

刚刚测试过这适用于您的数据:

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

另一种方法是使用mapWithKeys()收集方法:

collect($array)->mapWithKeys(function($i, $k) { return [$k => $i[0]['Amount']]; })

【讨论】:

  • 我在哪里收集result
  • 我将如何包含pricequantity 类似于Amount as here array_pluck($array, '*.Amount')
  • @EaB 您究竟想如何包含其他字段?你想得到像$2997 / 3 / 999这样的连接字符串吗?
  • 不像那样我想拥有一个html table 作为key : price : quantity : amount
  • @EaB 显示数据,不需要修改。只需使用@foreach ($array as $key => $item) {{ $key }} : {{ $item[0]['price'] }} @endforeach 对其进行迭代
【解决方案2】:

如果我理解正确,您正在寻找这个:

foreach ( $my_array as $key => $value )
{
    echo $key . ': ' . $value['Amount'];
}

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 2023-01-10
    • 2017-03-17
    • 2017-03-18
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多