Skip to content
Advertisement

PHP echo the lowest value from a list of dynamically generated array

I’m using a WordPress shopping theme and it displays the products details (price, colors etc) as json scripts, however I need to display at least the price as text. The developer was not very helpful and my php knowledge is limited to none, so I’m hoping this will be an easy/fast fix for someone here. This is the part of the script that generates the json:

if(is_array($product['skuAttr'])) {
    $str_data['offers'] = [];
    foreach ($product['skuAttr'] as $k => $attr) {
        $str_data['offers'][] = [
            "@type" => "Offer",
            "url" => $this_url . '?sku=' . $k,
            "priceCurrency" => $product['currency'],
            "price" => $attr['_salePrice_nc'],
            "priceValidUntil" => date('Y-m-d',
                strToTime('today + 30 days')
            ),
            "name" => $itemmeta['name'],
            "availability" => $attr['isActivity'] ? "https://schema.org/InStock" : "https://schema.org/OutOfStock",
            "itemCondition" => "https://schema.org/NewCondition"
        ];
        $min_saleprice = min($attr['_salePrice_nc']);  // that's mine

    }
}

…and later on:

<script type="application/ld+json">
    <?php echo json_encode($str_data); ?>
</script>

The $min_saleprice was my idea that I later echoed and, of course, it broke the site.

<?php echo $min_saleprice; ?>  /// not a chance

So, how to display the _salePrice_nc later in the document? Thank you.

If it matters, I am using the latest WordPress 5.6.1, PHP 7.2, nGinx and I need this to validate the products on Pinterest, whose scraper is not smart enough to get the price from the script, and I think it must find it in page as plain text. enter image description here

Advertisement

Answer

You made two critical errors:

  1. You were looking for the minimal price in the wrong place (you were trying to select the minimial value of a single price – it’s not an array).
  2. You were overwriting the variable in each iteration.

The correct place where you should look for the minimal value is the final array of all offers and it should be done outside the loop. The following code will achieve this:

$min_saleprice = min(array_column($str_data['offers'], 'price'));

The array_column function extracts all of the price values from $str_data['offers'] and then min selects the lowest of them.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement