2011-12-15 169 views
0
<?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]); 
?> 

我有以下代碼,並且目前其輸出: 原始值卸下最大值/最小值從陣列,取平均,輸出平均

Array 
(
    [0] => 199.95 
    [1] => 149.99 
    [2] => 129.99 
    [3] => 149.99 
    [4] => 149.99 
    [5] => 124.99 
    [6] => 225.99 
    [7] => 149.96 
    [8] => 149.99 
    [9] => 149.99 
    [10] => 184.99 
    [11] => 199.99 
    [12] => 184.98 
    [13] => 149.99 
    [14] => 326.99 
    [15] => 269.96 
    [16] => 348.95 
    [17] => 108.9 
    [18] => 149.99 
    [19] => 149.99 
    [20] => 229.99 
    [21] => 357.38 
    [22] => 169.96 
    [23] => 229.98 
    [24] => 187.99 
) 


max is 

應當移除所述陣列鍵[21]和[17],因爲它們是最大值和最小值。然後取沒有這兩個值的平均值並顯示它。

我該怎麼做到這一點?

+0

您已經提出這個基本問題了,它有很多答案:http://stackoverflow.com/questions/8468871/auto-delete-max-min-from-array-on-creation/8468910#8468910 – Jon 2011-12-15 02:35:36

回答

4
  1. 排序陣列(sort
  2. 移除第一元件(array_shift
  3. 刪除最後一個元件(array_pop
  4. 創建其餘陣列(array_sum
  5. 分的總和的與剩餘數組中的元素數相加(count)。

代碼示例:

sort($prices, SORT_NUMERIC); 
array_shift($prices); 
array_pop($prices); 
$sum = array_sum($prices); 
$average = $sum/count($prices); 
+0

謝謝爲步驟。我如何去基於價值進行排序。您給我的http://us.php.net/sort鏈接顯示按字母順序排序的示例,但不是按數字排序的示例。 – 2011-12-15 04:08:35

+0

你可以使用`SORT_NUMERIC`標誌。我添加了一個顯示它的代碼示例。 – hakre 2011-12-15 12:55:26

4

你可以使用sortarray_shiftarray_pop

sort($prices); // Sort the array from lowest to highest value 
array_pop($prices); // Remove the max value. Use $max = array_pop($prices); if you want to use the value 
array_shift($prices); // Remove the min value. Use $min = array_shift($prices); if you want to use the value 

echo array_sum($prices)/count($prices); // Echo the average without $max or $min 
0

你也可以使用array_summaxmincount

echo (array_sum($prices) - max($prices) - min($array))/count($prices); 
相關問題