按给定的值返回数组键(返回日期的月份)

时间:2016-08-24 05:36:32

标签: php arrays datetime multidimensional-array

我有一个带有键的PHP多维数组,下面的数组有日期。

Array (
    [123] => Array
    (
       [one] => 2016-01-22 10:32:15
       [two] => 2016-02-21 14:24:15
       [three] => 2016-02-12 11:00:15
    )

    [553] => Array
    (
       [one] => 2016-03-22 10:32:15
       [two] => 2016-02-21 14:24:15
       [three] => 2016-08-12 11:00:15
    )

)

我需要按月收到钥匙。例如:

$value = '2016-02';

return 123 -> 2
return 552 -> 1

如何才能实现这一目标的最佳方法? 谢谢。

1 个答案:

答案 0 :(得分:0)

您可以简单地执行以下操作。我稍微改变了一下代码。

<?php
$date = Array (
123 => Array
(
   "2016-01-22 10:32:15",
   "2016-02-21 14:24:15",
   "2016-02-12 11:00:15"
),
553 => Array
(
   "2016-03-22 10:32:15",
   "2016-02-21 14:24:15",
   "2016-08-12 11:00:15"
)
);
$givenDate = "2016-02";
$givenMonth = explode("-",$givenDate)[1];

foreach ($date as $key => $value){
    foreach ($value as $k => $v){
        $d = explode(" ", $v);
        $d = explode("-", $d[0]);
        if($d[1] ==$givenMonth ){
            echo $key."=>".$k."<br/>";
        }
    }
}