Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-delete Max/Min from Array on creation

Updated Code that creates array, but ISNT outputting the min/max values. Why isnt this working and how do I get it to automatically remove the min/max value and then reoutput the array?

<?php 
$url = 'https://www.googleapis.com/shopping/search/v1/public/products?key=thekey&country=US&q=nintendo+wii';

$data = curl_init($url);
curl_setopt($data, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($data, CURLOPT_HEADER, 0);

$product_result = curl_exec($data);
curl_close($data);


$arr = json_decode($product_result, true);
$prices = array();

echo "Original Values";

foreach ($arr['items'] as $item)
{
    if (isset($item['product']['inventories'][0]['price']))
    {
        $prices[] = $item['product']['inventories'][0]['price'];
    }
}


echo '<pre>';
print_r($prices);
echo '<br /><br />';

// Get the values
$min = $prices[$minIndex];
$max = $prices[$maxIndex];

// Find the values
$minIndex = array_search($min, $prices);
$maxIndex = array_search($max, $prices);

#print out results with no min/max pair
echo $prices[$min] . 'max is ' . $prices[$max];
echo '</pre>';
// Unset the values
unset($prices[$minIndex], $prices[$maxIndex]);
?>

Current Output of the code that doesn't seem to show the min/max value:

Original Values
Array
(
    [0] => 149.99
    [1] => 149.99
    [2] => 149.99
    [3] => 209.95
    [4] => 124.99
    [5] => 225.99
    [6] => 149.96
    [7] => 249.99
    [8] => 193.99
    [9] => 149.99
    [10] => 149.99
    [11] => 149.99
    [12] => 326.99
    [13] => 269.96
    [14] => 258.99
    [15] => 129.99
    [16] => 149.99
    [17] => 39.99
    [18] => 149.99
    [19] => 209.99
    [20] => 349.95
    [21] => 357.38
    [22] => 169.96
    [23] => 125
    [24] => 149.99
)


max is 
like image 898
Yo Bro Avatar asked Jul 22 '26 03:07

Yo Bro


1 Answers

Based on unset and array_search from php.net, this should work:

// Find the values
$minIndex = array_search($minVal, $prices);
$maxIndex = array_search($maxVal, $prices);

// Get the values
$min = $prices[$minIndex];
$max = $prices[$maxIndex];

// Unset the values
unset($prices[$minIndex], $prices[$maxIndex]);

// Print out values
echo 'min value: '.$min;
echo 'max value: '.$max;

// Print full array
print_r($prices);
like image 91
Jon Egeland Avatar answered Jul 23 '26 17:07

Jon Egeland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!