2013-10-07 31 views
1

我試圖從任何列中獲取列值中包含「xx」的最小值。如何從陣列行中獲取最小值

下面是我的代碼:

<?php 
$array = array(
array(
    'id' => 1, 
    '10xx' => 14, 
    '11xx' => 32, 
    '12xx' => 4 
), 

    array(
    'id' => 2, 
    '10xx' => 13, 
    '11xx' => 36, 
    '12xx' => 41 
) 
); 



foreach($array as $item) 
{ 
$lowestKey = ''; 
foreach($item as $key => $value) 
{ 


    if(strpos($key, 'xx') === 0) 
    { 

    if($lowestKey == '') 
    { 
    $lowestKey = $key; 
    } 
    else 
    { 
    if($value < $item[$lowestKey]) 
    { 
    $lowestKey = $key; 
    } 
    } 
    } 
} 

echo 'lowest for id ' . $item['id'] . ': ' . $item[$lowestKey] . "\n"; 
} 
?> 
+1

「但我不能」 - _why_?什麼是輸出?另外,看看http://php.net/manual/en/array.sorting.php – akluth

+0

http://php.net/manual/en/function.min.php –

回答

2

你有一個函數已經爲它:

http://php.net/manual/en/function.min.php

echo min(2, 3, 1, 6, 7); // 1 
echo min(array(2, 4, 5)); // 2 

echo min(0, 'hello');  // 0 
echo min('hello', 0);  // hello 
echo min('hello', -1); // -1 

與array_values結合起來,如果這更符合您的需求。

0

而不是循環再次使用min()函數。

$lowest_keys = array(); 

foreach($array as $item) 
{ 
    unset($item[ 'id' ]); 
    $lowest_keys[] = min($item); 
} 
+0

你忘了'id'是也在陣列中,哪輛車導致最低的鑰匙 – MKroeders

+0

@ Hendriq,很好的發現,沒有注意到,謝謝 –

0
function find_lowest($array){ 
     $new_array = array(); 
     foreach($array as $key => $val){ 
      if(is_array($val)){ 
       $new_array[$key] = find_lowest($val); 
      }else{ 
       $new_array[$key] = $val ; 
      } 
     } 
     return min($new_array); 

    } 
    $array = array(array( 'id' => 1, 
    '10xx' => 14, 
    '11xx' => 32, 
    '12xx' => 4 
), 

    array(
    'id' => 2, 
    '10xx' => 13, 
    '11xx' => 36, 
    '12xx' => 41 
) 
); 
echo find_lowest($array); 
2
function _getNumber($array) { 
    return $array['id']; 
} 
$numbers = array_map('_getNumber', $array); 

OR

$numbers = array_map(function($array) { 
    return $array['id']; 
}, $array); 

echo $min = min($numbers); 
echo $max = max($numbers); 
0
$array = array(
     array(
      'id' => 14, 
      '10xx' => 14, 
      '11xx' => 32, 
      '12xx' => 4 
     ), 

      array(
      'id' => 2, 
      '10xx' => 13, 
      '11xx' => 36, 
      '12xx' => 41 
     ) 
     ); 

    $lowestKey = ''; 

    foreach($array as $arra){ 
     foreach ($arra as $key=>$value){ 
      if ($key == 'id'){ 
       if(($value < $lowestKey)||($lowestKey== '')){ 
       $lowestKey = $value; 
       } 
      } 


     } 
    } 
    echo $lowestKey; 
相關問題