如何减少数组值的一部分?

时间:2011-08-05 11:01:51

标签: php arrays multidimensional-array arraylist

我有一个格式为

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

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

输出应为

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

怎么做?

6 个答案:

答案 0 :(得分:2)

像Fernaref解释的那样:通过解析它们的价值来根据您的需要更改密钥。有多种方法可以实现这一点,这只是一个例子(Demo):

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

答案 1 :(得分:1)

这是一个字符串 - 你必须解析数据,递减值并将密钥重新组合在一起。或者首先使用更好的密钥。

答案 2 :(得分:0)

$newArray = array();
foreach ($array as $key => $value)
{
  $newKey = someFunction($key);
  $newArray[$newKey] = $value;
}

虽然“someFunction”会将您的日期转换为创建新密钥

答案 3 :(得分:0)

试试这个:

$result = array();
foreach ($array as $key => $val) {
  $date = strtotime ($key);

  $result[date("Y-m-d", strtotime("- month", $date)] = $val;
}

答案 4 :(得分:0)

某些功能可以

preg_replace("@(\d\d\d\d)-(\d\d)@e","'\$1-'.str_pad($2-1, 2, '0', STR_PAD_LEFT)",$key);

答案 5 :(得分:0)

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