2014-09-24 3 views
1

날씨 값이 포함 된 배열이 있습니다. 이제 온도로 배열을 정렬하고 온도에 대한 최대 값을 꺼내 작업 PHP 스크립트를 가지고, 나는 다시 압력으로 배열을 정렬하고 최대 압력 값을 얻을.usort와 함께 사용할 때 함수를 결합 하시겠습니까?

function compare_pressure($a, $b) 
{ 
    return strnatcmp($a['pressure'], $b['pressure']); 
} 

function compare_temp($a, $b) 
{ 
    return strnatcmp($a['temp'], $b['temp']); 
} 

usort($table, 'compare_pressure'); 
$mypress = $table[0]['pressure']; 

usort($table, 'compare_temp'); 
$mytemp = $table[0]['temp']; 

내가 지금은 각각의 비교를위한 새로운 하나를 작성 유지해야 그나마 있도록 위의 기능을 결합하기 위해 노력하고 있어요,하지만 난에 usort와 함께 사용할 때 운이있을 것 같다하지 않습니다. 당신은 단지 최대 필요한 경우

// Method 1 -- by object 
class Comparitor { 
    public function __construct($key) { 
     $this->key = $key; 
    } 
    public function compare($a, $b) { 
     return strnatcmp($a[$this->key], $b[$this->key]); 
    } 
} 
usort($table, [new Comparitor('temp'), 'compare']); 

// Method 2 -- anonymous function 
function compare_by_key($a, $b, $key) { 
    return strnatcmp($a[$key], $b[$key]); 
} 
usort($table, function ($a, $b) { return compare_by_key($a, $b, 'temp'); }); 

// Method 3 -- by global 
function compare_by_global_key($a, $b) { 
    global $key; 
    return strnatcmp($a[$key], $b[$key]); 
} 
$key = 'temp'; 
usort($table, 'compare_by_global_key');  

것은, 당신이 사용할 수 있습니다

나는 우선 순위의 방법 일 :(

function compare_temp($a, $b, $value) 
{ 
    return strnatcmp($a[$value], $b[$value]); 
} 

usort($table, 'compare_temp', 'temp'); 
+1

왜 두 번 정렬합니까? 당신은 단지 배열을 foreach() 할 수 있고'if ($ cur> $ prev)'를 사용하여 압력과 온도 값을 테스트 할 수 있습니다. 배열이 2 개의 본격적인 배열이 아닌 1 개의 루프 루프 –

+0

배열을 배열하는 데 가장 좋은 방법이 될까요? 배열에는 약 300 개의 항목으로 정렬해야하는 약 15 개의 값이 있습니다. 나는 15 개의 값을 정렬하는 것보다 쉽게 ​​만들 수 있다고 생각한다. – Greg

답변

1

많은 나던 같은 것을, 필요 :

function aggregate_by_key($table, $key, $aggregate = 'max') { 
    return $aggregate(array_column($table, $key)); 
} 
$maxTemp = aggregate_by_key($table, 'temp', 'max'); 
$minTemp = aggregate_by_key($table, 'temp', 'min'); 
$sumTemp = aggregate_by_key($table, 'temp', 'array_sum'); 
+0

내가 언급하는 것을 잊어 버린 한가지는 최대 값뿐만 아니라 그 값과 관련된 해당 시간을 필요로한다는 것입니다. – Greg

+0

@ 그렉 : 아, 접근 방식에 큰 변화가 있습니다! :) – bishop

+0

감사합니다 - 방법 1을 사용하여 모든 작업을 수행했습니다. – Greg

0
function createComparisonFunction($key) { 
    return function ($a, $b) use ($key) { 
     return strnatcmp($a[$key], $b[$key]); 
    }; 
} 

usort($table, createComparisonFunction('pressure')); 
usort($table, createComparisonFunction('temp')); 

갖는 SAI D, 즉, 차라리 시작하는이 방법을 사용하십시오 :

$max = array_reduce(
    $table, 
    function (array $max, array $value) { 
     if (strnatcmp($max['temp'], $value['temp']) < 0) { 
      $max['temp'] = $value['temp']; 
     } 
     if (strnatcmp($max['pressure'], $value['pressure']) < 0) { 
      $max['pressure'] = $value['pressure']; 
     } 
     return $max; 
    }, 
    ['temp' => null, 'pressure' => null] 
); 

echo $max['temp']; 
echo $max['pressure']; 

난 당신이에 콜백 함수를 단순화 것이다, strnatcmp 정말, 그 값은 정수이어야한다 필요한 이유를 잘 모르겠어요 :

function (array $max, array $value) { 
     $max['temp']  = max($max['temp'], $value['temp']); 
     $max['pressure'] = max($max['pressure'], $value['pressure']); 
     return $max; 
    } 
나는 전체 프로세스 encaptulate하는 클래스 만들 유혹 될 것이다
+0

감사합니다. 훨씬 간단 해 보입니다! – Greg

0

:

class WeatherData{ 

    private $max_values; 

    public function __construct($weather_array, $elements){ 

     foreach ($weather_array as $weather_item) { 
      foreach($elements as $element){ 
       if(!isset($this->max_values[$element])){ 
        $this->max_values[$element] = $weather_item[$element]; 
       }else{ 
        if($this->max_values[$element] < $weather_item[$element]){ 
         $this->max_values[$element] = $weather_item[$element]; 
        } 
       } 
      } 
     }  
    } 

    public function __get($key){ 
     return $this->max_values[$key]; 
    } 

} 

$wa = array(
    array('pressure'=>11, 'temp'=>2), 
    array('pressure'=>1, 'temp'=>22), 
    array('pressure'=>7, 'temp'=>21), 
    array('pressure'=>22, 'temp'=>33), 
    array('pressure'=>16, 'temp'=>8), 
); 
$elements = array(
    'temp', 'pressure' 
); 
$wd = new WeatherData($wa, $elements); 

echo 'max temp: '. $wd->temp . ' max pressure :' . $wd->pressure; 

라이브 예 : http://codepad.viper-7.com/kobe1Z

관련 문제