如何打印多维数组中数量非零的商品颜色库存信息?
解决方法
首先明确需求:仅处理jeans和shirts两类商品,过滤掉数量为0的颜色条目,按指定格式输出库存信息。用两层foreach循环就能实现,具体代码如下:
// 你的库存数组 $inventory = [ 'jeans' => [ 'blue' => 3, 'pink' => 1, 'red' => 0 ], 'shirts' => [ 'blue' => 5, 'pink' => 0, 'red' => 0 ], 'pijama' => [ 'blue' => 0, 'pink' => 0, 'red' => 0 ] ]; // 定义需要处理的目标品类 $targetCategories = ['jeans', 'shirts']; // 外层循环遍历所有品类 foreach ($inventory as $category => $colors) { // 跳过非目标品类 if (!in_array($category, $targetCategories)) { continue; } // 内层循环遍历当前品类的颜色和数量 foreach ($colors as $color => $count) { // 过滤数量为0的条目 if ($count <= 0) { continue; } // 格式化品类名首字母大写,匹配示例格式 $formattedCategory = ucfirst($category); // 处理单复数:数量为1时用item,否则用items $itemText = $count == 1 ? 'item' : 'items'; echo "\"{$formattedCategory} has {$count} {$color} {$itemText}.\"\n"; } }
代码说明:
- 用
$targetCategories明确要处理的品类,后续新增品类直接修改这个数组即可,灵活性更高。 - 外层循环遍历整个库存,拿到每个品类的名称和对应颜色库存。
- 通过
in_array判断当前品类是否在目标列表,不在则跳过。 - 内层循环遍历颜色和数量,直接过滤掉数量≤0的条目。
- 额外处理了单复数和品类名大小写,让输出更符合语言习惯和示例要求。
运行代码后输出结果:
"Jeans has 3 blue items." "Jeans has 1 pink item." "Shirts has 5 blue items."
内容的提问来源于stack exchange,提问作者Mikasa
相关产品推荐
相关产品推荐

