2011-12-12 3 views
3

어레이를 생성하지만 ISNT가 최소/최대 값을 출력하는 코드가 업데이트되었습니다. 왜이 방법이 효과가 없으며 최소/최대 값을 자동으로 제거한 다음 어레이를 다시 출력하려면 어떻게해야합니까?작성시 배열에서 최대/최소 자동 삭제

<?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]); 
?> 
최소/최대 값을 표시하지 않는 것 코드의

전류 출력 : unset 및 php.net에서 array_search을 바탕으로

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 
+1

한 방법과 동일합니다 : 해제 ($ 가격이 [array_search ($의 MINVAL가)]); 해제 ($ 가격은 [($의 MAXVAL) array_search]) 나는이 설정되지 않은 방법을 보았지만 –

+0

은 키 예를 보았다 php.net에. 어쨌든 다음 행을 실행하기 위해 배열을 재설정하십시오 :'echo "min is". $ minval. "
최대 값입니다." $ maxval. "
평균은"입니다. $ avgofval;' 여전히 orig max/min 쌍으로 초기 배열에서 계산 된 것으로 보입니다. –

답변

1

이 작동합니다 :

// 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); 
+0

@Dagon 죄송합니다. 귀하의 의견을보기 전에 답변을 게시했습니다. – Jon

+0

이것은 다음과 같은 경고를 제공합니다 : array_search는 2 개 이상의 매개 변수를 허용합니까? –

+0

그걸 놓쳐 버렸어, 지금 고쳐라. – Jon

0

숫자 순서로 배열을 정렬 한 다음 array_pop() 및 array_shift()를 사용하여 배열 할 수 있습니다.

sort($prices,SORT_NUMERIC); 
    $maxval = array_pop($prices); 
    $minval = array_shift($prices); 

    $avgofval = (count($prices)) 
       ? array_sum($prices)/count($prices) 
       : 0; 

    echo "min is ". $minval . "<br>Max is ". $maxval . "<br />avg is " . $avgofval ; 
    echo '<pre>'.print_r($prices,1).'</pre>'; 
+0

그다지 많은 부가가치가없는 많은 추가 작업이 있습니다. – Jon

+0

3 문장이 필요합니다. 접근 방법은 5 개가 필요합니다 (최소/최대 2 개, 키 찾기 2 개, 값 삭제 1 개) –

+0

제 접근 방식은 읽기 목적으로 분리되어 있습니다. 단 하나의 라이너이지만, 실제로 그 점을 보여주는 것은 아닙니다. – Jon

0

$minVal$maxVal은 배열 검색 호출 전에 정의되지 않습니다.

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

그리고 array_search는 값을 찾지 못합니다. 키를 찾습니다. 바늘이 배열에서 발견되면 키를 반환하고 그렇지 않으면 FALSE를 반환합니다.

$minIndexFALSE이며, $maxIndexFALSE입니다.

숫자가

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

가능한 솔루션이다 .. 또한 잘못된 :

$minValue = FALSE; 
$maxValue = 0; 
foreach ($arr['items'] as $item) { 
    if (isset($item['product']['inventories'][0]['price']) !== false) { 
     $price = $item['product']['inventories'][0]['price']; 
     $prices[] = $price; 
     if (! $minValue || $minValue < $price) { 
      $minValue = $price; 
     } 
     if ($price > $maxValue) { 
      $maxValue = $price; 
     } 
    } 
} 

제외

if (isset($item['product']['inventories'][0]['price']) !== false) { ... } 

가 중복 검사이다. 그것은 정확히

if (isset($item['product']['inventories'][0]['price'])) { ... } 
+0

이것은 많이하지 않습니다. 업데이트 된 코드를 참조하십시오. 귀하의 회신에 감사드립니다. –