2013-10-01 29 views
2

我有如下数组:PHP检索最小值在2D关联数组

Array 
    (
    [0] => Array 
     (
       [id] => 1 
       [price1] => 16 
       [price2] => 10 
       [price3] => 3 
     ) 

    [1] => Array 
     (
      [id] => 2 
      [price1] => 19 
      [price2] => 2 
      [price3] => 6 
     ) 

    [2] => Array 
     (
      [id] => 3 

      [price1] => 14 
      [price2] => 32 
      [price3] => 1 
     ) 

) 

我想从每行独立于其他行较低的价格。例如对于id=1,较低的价格是3,对于id=2较低的是2等等。任何想法如何自动化这一点。

+0

您可能需要使用''分在'foreach'环()。 http://php.net/manual/en/function.min.php – Mina

回答

1

可能的解决办法:

Demo

foreach($array as $item) 
{ 
    $lowestKey = ''; 
    foreach($item as $key => $value) 
    { 
     if(strpos($key, 'price') === 0) 
     { 
      if($lowestKey == '') 
      { 
       $lowestKey = $key; 
      } 
      else 
      { 
       if($value < $item[$lowestKey]) 
       { 
        $lowestKey = $key; 
       } 
      } 
     } 
    } 

    echo 'lowest for id ' . $item['id'] . ': ' . $item[$lowestKey]; 
} 

这种方法的好处是:

  • 价格键不必是连续的,甚至数值。任何以price开头的密钥都视为价格。
  • 可以有无限的价格,它不限于三个。
  • 存储在数组中的任何其他数据都不会影响它或破坏任何内容。例如,如果将来您添加了一个description密钥,它不会影响代码或需要进行任何修改。
+0

非常感谢,它完美的工作 –

-1

尝试可以帮助:

$price = array(); 
foreach($array as $key=>$each){ 
    $low = $each['price1']; 
    if($each['price2'] < $low){ 
     $low = $each['price2']; 
    } 
    if($each['price3'] < $low){ 
     $low = $each['price3']; 
    } 
    $price[$key] = $low; 
} 

print_r($price); 
0

试试这个:

$newarray = array(); 
foreach ($array as $row) 
{ 
    $id = $row['id']; 
    unset($row['id']); 
    $newarray[$id] = min($row); 
} 

你去那里。 $newarray现在包含每行的id => {lowest value}

0
$r = array_reduce($array, function(&$result, $item) { 

    $key = $item['id']; 
    unset($item['id']); 
    $result[$key] = min($item); 
    return $result; 

}); 
0

尝试以下:

$prices = array(0 => array ('id' => 1, 
         'price1' => 16, 
         'price2' => 10, 
         'price3' => 3 
         ), 

      1 => array ('id' => 2, 
         'price1' => 19, 
         'price2' => 2, 
         'price3' => 6 
       ), 

      2 => array ('id' => 3, 
         'price1' => 14, 
         'price2' => 32, 
         'price3' => 1 
       ) 

    ); 



foreach($prices as $price) { 
    $tmp_arr = array(0=> $price['price1'], 1=> $price['price2'], 2=> $price['price3']); 
    sort($tmp_arr); 
    $arr_low_price = array('id'=> $price['id'], 'low_price' => $tmp_arr[0]); 
    print_r($arr_low_price); 
    echo '<br />'; 
}