2011-08-05 52 views
0

我在格式如何減少數組的值中的一部分?

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

我需要T0由1即[ 「2011- -29」]遞減中間鍵值爲[「2011- 陣列 - 29" ]

輸出應該是

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

如何做到這一點?

回答

1

這是一個字符串 - 你必須解析數據,減少數值並把密鑰放在一起。或者首先使用更好的鑰匙。

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

雖然 「someFunction」 將轉換您的日期,以創建新的密鑰

0

試試這個:

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

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

-1,不適合我的工作。 '-1個月'或者你只將數組減少到一個鍵,另外,如果鍵不是有效的日期來進行減法,它將被刪除/覆蓋。比較:http://codepad.org/4ACdinyA – hakre

0

somefunction可以

preg_replace("@(\d\d\d\d)-(\d\d)@e","'\$1-'.str_pad($2-1, 2, '0', STR_PAD_LEFT)",$key); 
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); 
+0

使用substr填充月份編號的好方法。我必須記住那一個! – Flambino

+0

@Flambino:實際上我太懶得查找它的sprintf符號,這太好了:'$ month = sprintf(「%02d」,$ month-1);' - 編輯過(但感謝反饋:)) 。 – hakre

+0

@hakre非常感謝,它工作得很好。 – Ezhil

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