查看价格历史/更改的php数组时,查看价格是否为零

时间:2013-11-28 14:00:14

标签: php

我在这个数组(date,pricechange)中有所有的价格变化。它始终按日期顺序排列:

$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数组,但我不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

尝试:

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

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

答案 1 :(得分:0)

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