在查看价格历史/变化的php数组时,找出价格是否为零


Find out if the price was zero when looking through php array of price history/changes

我在这样的数组中有所有的价格变化(日期,价格变化)。它总是按日期顺序排列:

$pricehistory = array (
    '2013-11-04' => 10,
    '2013-11-10' => 0,
    '2013-12-01' => 10
);

我需要的是弄清楚某个特定日期的价格是否为零。

function was_free($date) {
    // return boolean
}
was_free('2013-11-11'); //should return true;
was_free('2013-12-01'); //should return false;

有人能帮我弄清楚怎么做吗?我想我需要反向循环$pricehistory数组,但我不确定如何执行。

//$default - returned if price is not exits 
function was_free($price_history, $current_date, $default = FALSE) {
    if(isset($price_history[$current_date]))
    {
        return empty($price_history[$current_date]);
    }
    $current_timestamp = strtotime($current_date);
    $history_timestamp = array();
    foreach ($price_history as $date => $price)
    {
        $history_timestamp[strtotime($date)] = $price;
    }
    $history_timestamp[$current_timestamp] = NULL;
    ksort($history_timestamp);
    $previous_price = ($default) ? FALSE : TRUE;
    foreach ($history_timestamp as $timestamp => $price)
    {   
        if($timestamp == $current_timestamp)
        {           
            break;
        }
        $previous_price = $price;
    }
    return empty($previous_price);
}

$price_history = array (
    '2013-11-04' => 10,
    '2013-11-10' => 0,
    '2013-12-01' => 10
);
// run !!
var_dump(was_free($price_history, '2013-11-03'));
var_dump(was_free($price_history, '2013-11-04'));
var_dump(was_free($price_history, '2013-11-09'));
var_dump(was_free($price_history, '2013-11-10'));
var_dump(was_free($price_history, '2013-11-11'));
var_dump(was_free($price_history, '2013-12-01'));
var_dump(was_free($price_history, '2013-12-02'));

尝试:

function was_free($date) {
    return array_key_exists($date,$pricehistory) && $pricehistory[$date] === 0;
}

由于$pricehistory不在函数的范围内,您可以将其作为参数传递或使用global访问它。