Home > Software design >  Printing multidimensional array values
Printing multidimensional array values

Time:09-16

I have an array of this type, Using this code

$myarray = get_post_meta( $product->get_ID(), 'wcb2b_product_group_prices' );
print_r($myarray);

prints me:

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] => ) ) ) 

Updated code:

$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;
        }
    }
}

I would be able to print the [regular_price][sale_price] Value.

How do you do that?

Thanks for help

CodePudding user response:

The below should do what you're looking for...

if ( $group_prices = get_post_meta( $product->get_ID(), 'wcb2b_product_group_prices', true ) ) {
    foreach ( $group_prices as $group => $group_price ) {
        $regular_price = $group_price[ 'regular_price' ] ?? null;
        $sale_price = $group_price[ 'sale_price' ] ?? null;

        if ( $regular_price ) {
            echo '<strong>Regular price for group ' . $group . ':</strong> ' . wc_price( $regular_price ) . '<br>';
        }
        
        if ( $sale_price ) {
            echo '<strong>Sale price for group ' . $group . ':</strong> ' . wc_price( $sale_price ) . '<br>';
        }
    }
}

This will output something like...

<strong>Regular price for group 449:</strong> $20.00<br>
<strong>Regular price for group 9609:</strong> $20.00<br>
  1. First we set the 3rd parameter for get_post_meta to true which removes the first level of the array which is unnecessary.
  2. We then loop through the groups and get regular and sale prices for each group, checking if they have values before printing.
  3. Finally, we print the price using the WooCommerce core wc_price() function which will format the price value with the currency symbol.
  •  Tags:  
  • php
  • Related