如何在PHP中正确打印含未知键的解码JSON
解决方案:按「数组键:金额」格式打印JSON内容
你不需要依赖reset()和key()来实现这个需求,直接通过foreach遍历解码后的对象或数组就能轻松拿到每个顶级键对应的金额,下面给你两种可行的实现方案:
方案1:处理已解码的stdClass对象
假设你已经将JSON解码为stdClass对象(比如通过json_decode($jsonString)),可以直接遍历对象的属性,每个属性对应的值是一个数组,取数组第一个元素的Amount字段即可:
// 假设$decodedData是你解码后的stdClass对象 foreach ($decodedData as $itemKey => $itemArray) { // 每个itemArray都是仅含一个元素的数组,直接取第一个元素的Amount $amount = $itemArray[0]->Amount; // 按要求格式输出 echo "{$itemKey}: {$amount}\n"; }
代码解释:
foreach ($decodedData as $itemKey => $itemArray):遍历stdClass对象的所有顶级属性,$itemKey就是你要的「数组键」(比如cigratte_flake),$itemArray是该键对应的数组。$itemArray[0]->Amount:因为每个数组里只有一个包含金额的对象,直接通过索引0获取这个对象,再访问它的Amount属性。
方案2:直接处理原始JSON字符串(解码为关联数组)
如果你还没解码JSON,或者更习惯用数组操作,可以将JSON解码为关联数组(给json_decode传第二个参数true),再进行遍历:
$rawJson = '{"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"}]}'; // 解码为关联数组 $dataArray = json_decode($rawJson, true); foreach ($dataArray as $itemKey => $itemList) { // 取数组第一个元素的Amount字段 $amount = $itemList[0]['Amount']; // 按要求格式输出 echo "{$itemKey}: {$amount}\n"; }
代码解释:
json_decode($rawJson, true):将JSON字符串解码为关联数组,方便通过键名直接访问值。$itemList[0]['Amount']:和方案1逻辑一致,取数组第一个元素的Amount值。
两种方案执行后都会输出你想要的格式:
cigratte_flake: 2997 wrestling_board: 800 flex_board_naga_dhaga: 600 total: 4397
内容的提问来源于stack exchange,提问作者user5405873
相关产品推荐
相关产品推荐

