PHP 检索二维关联数组中的最小值


PHP Retrieve minimum values in a 2D associative array

>我有以下数组:

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,依此类推。任何知道如何自动化这一点。

可能的解决方案:

演示

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密钥,则不会影响代码或需要进行任何修改。

试试这个:

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

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

$r = array_reduce($array, function(&$result, $item) {
    $key = $item['id'];
    unset($item['id']);
    $result[$key] = min($item);
    return $result;
});

尝试以下操作:

$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 />';
}

尝试可能会有所帮助:

$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 );