如何打印多维数组中的regular_price与sale_price字段值?
问题描述
我通过以下代码获取产品的批量价格数组:
$myarray = get_post_meta( $product->get_ID(), 'wcb2b_product_group_prices' ); print_r($myarray);
输出的数组结构如下:
Array ( [0] => Array ( [428] => Array ( [regular_price] => [sale_price] => ) [449] => Array ( [regular_price] => 20.00 [sale_price] => ) [9609] => Array ( [regular_price] => 20.00 [sale_price] => ) ) )
我尝试了这段循环代码,但无法清晰输出每个组的regular_price和sale_price值:
$myarray = get_post_meta( $product->get_ID(), 'wcb2b_product_group_prices' ); //print_r($myarray); foreach ($myarray as $key => $value) { // print_r($value); foreach ($value as $key2 => $value2) { // print_r($value2); foreach ($value2 as $key3 => $value3) { echo $value3; } } }
请问如何正确打印出数组中的regular_price和sale_price的值?
解决方案
可以直接针对数组的嵌套结构进行针对性遍历,同时添加文本标识让输出更清晰:
$myarray = get_post_meta( $product->get_ID(), 'wcb2b_product_group_prices' ); // 取出外层数组的第一个元素,这才是实际的价格组数据集合 $priceGroups = $myarray[0]; // 遍历每个价格组 foreach ($priceGroups as $groupId => $priceData) { echo "组ID: {$groupId}\n"; // 输出常规价格,为空时显示"未设置" echo "常规价格: " . ($priceData['regular_price'] ?: '未设置') . "\n"; // 输出促销价格,为空时显示"未设置" echo "促销价格: " . ($priceData['sale_price'] ?: '未设置') . "\n\n"; }
代码说明:
- 首先从
$myarray中取出索引为0的元素,因为get_post_meta默认返回包含单元素的数组,这个元素才是我们需要的价格组集合。 - 遍历每个价格组时,直接通过键名
regular_price和sale_price获取对应的值,不需要嵌套三层循环。 - 使用
?:运算符处理空值情况,避免输出空白内容,让结果更易读。
如果只需要输出所有非空的价格值,也可以简化成:
$myarray = get_post_meta( $product->get_ID(), 'wcb2b_product_group_prices' ); $priceGroups = $myarray[0]; foreach ($priceGroups as $priceData) { if (!empty($priceData['regular_price'])) { echo "常规价格: {$priceData['regular_price']}\n"; } if (!empty($priceData['sale_price'])) { echo "促销价格: {$priceData['sale_price']}\n"; } }
内容的提问来源于stack exchange,提问作者emiliano
相关产品推荐
相关产品推荐

