如何在PHP中更改我的数组格式

时间:2015-06-04 09:12:53

标签: php arrays date converter

我的代码生成这样的数组

Array
(
[0] => Array
    (
        [0] => 2015-05-28
        [1] => 1
    )
[1] => Array
    (
        [0] => 2015-05-29
        [1] => 1
    )
[2] => Array
    (
        [0] => 2015-06-02
        [1] => 2
    )
)

我希望将其转换为与bellow相同的

array(
    [0] => Array
    (
        [0] => 05
        [1] => 2
    )
    [1] => Array
    (
        [0] => 06
        [1] => 2
    )
);

如何在第一个月转换数组,然后再转换第二个值

3 个答案:

答案 0 :(得分:4)

非常简单的解决方案:

foreach($array as $date=>$entry) {
    $month = substr($date, 3, 2); // <-- this requires the date strings to always have the exact same structure
    if(!isset($newArray[$month]))
        $newArray[$month] = 0;
    $newArray[$month] += $entry;
}

答案 1 :(得分:2)

key中提取月份,然后检查输出数组中的月份是否存在。

<?php

$array = array(
    array(
        '2015-05-28',
        1
    ), array(
        '2015-05-29',
        1
    ), array(
        '2015-06-02',
        2
    )
);

$output = array();

foreach ($array as $val) {
    $month = date('m', strtotime($val[0]));

    if (isset($output[$month])) {
        $output[$month] += $val[1];
    } else {
        $output[$month] = $val[1];
    }
}

echo '<pre>';

print_r($output);

/*
    Array
    (
        [05] => 2
        [06] => 2
    )
*/

?>

答案 2 :(得分:0)

$array = array(
    array(
       '2015-05-28',
        1
    ), 
    array(
       '2015-05-29',
        1
    ), 
    array(
       '2015-06-02',
        2
    )
 );


 $output = array();
 $a=array();
 $b=array();
 foreach ($array as $val) {
    $month = date('m', strtotime($val[0]));
      if (isset($output[$month])) {
            $output[$month] += $val[1];
        } else {
            $output[$month] = $val[1];
        }
      }
      foreach (  $output as $key => $value) {
           $b[] = array($key,$value);
      }
 }