如何递减数组值中的一部分



我有一个格式的数组

array() {["2011-07-29"]=> 39 ["2011-07-30"]=> 39 ["2011-07-31"]=> 39 ["2011-08-01"]=> 40}

我需要将中间键值递减1,即["2011-07-29"]到["2011-06-29"]

输出应该是

array() {["2011-06-29"]=> 39 ["2011-06-30"]=> 39 ["2011-06-31"]=> 39 ["2011-07-01"]=> 40}

如何做到这一点?

正如Fernanref所解释的:通过解析密钥的值,根据需要更改密钥。有多种方法可以实现这一点,这只是一个例子(演示(:

<?php
$data = array(
  '2011-07-29' => 39,
  '2011-07-30' => 39,
  '2011-07-31' => 39,
  '2011-08-01' => 40,
);
$keys = array_keys($data);
foreach($keys as &$key)
{
    list(,$month) = sscanf($key, '%d-%d-%d');
    $month = sprintf("%02d", $month-1);
    $key[5] = $month[0];
    $key[6] = $month[1];
}
unset($key);
$data = array_combine($keys, $data);
print_r($data);

这是一个字符串-您必须解析出数据,递减值,然后将键放回一起。或者先用一把更好的钥匙。

试试这个:

$result = array();
foreach ($array as $key => $val) {
  $date = strtotime ($key);
  $result[date("Y-m-d", strtotime("- month", $date)] = $val;
}
$input = array("2011-07-29"=>39, "2011-07-30"=>39, "2011-07-31"=>39, "2011-08-01"=>40);
$output = array();
foreach($input as $key => $value) {
    $key = preg_replace_callback("/(d{4})-(d{2})-/", function($match) {
        $match[2] = (int) $match[2] - 1;
        if( $match[2] < 1 ) { // don't forget to decrement the year, if the month goes below 1
            $match[1] = (int) $match[1] - 1;
            $match[2] = 12;
        }
        return $match[1] . "-" . str_pad($match[2], 2, "0", STR_PAD_LEFT) . "-";
    }, $key);
    $output[$key] = $value;
}
print_r($output);

某些函数可以是

preg_replace("@(dddd)-(dd)@e","'$1-'.str_pad($2-1, 2, '0', STR_PAD_LEFT)",$key);
$newArray = array();
foreach ($array as $key => $value)
{
  $newKey = someFunction($key);
  $newArray[$newKey] = $value;
}

而"someFunction"将转换您的日期以创建新密钥

相关内容

  • 没有找到相关文章