【问题标题】:Store record inside parent array在父数组中存储记录
【发布时间】:2017-07-12 15:36:12
【问题描述】:

我有列 date_added,它的格式日期为 2017-02-09 08:45:48。我想将同一月份的所有记录存储在该特定月份内,例如二月记录应该在二月数组内。我正在尝试以下代码。

$Res = array();
        $query   = $this->pdoConnection->prepare("select id,date from `record` ");
        $query->execute();
        header("Content-type: application/json; charset=utf-8");
        $month = array(1,2,3,4,5,6,7,8,9,10,11,12);
        while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
            $Data = $row;
            $array_date = date("m", strtotime($row['date']));
            $alpha_month = date("M", strtotime($row['date']));
            if(in_array($array_date,$month)){
                $Res[] = array($alpha_month=>array($Data));
            }
        }

        $output = array(
            'response' => $Res
        );  

        echo json_encode($output,JSON_PRETTY_PRINT);

结果

{
    "response": [
        {
            "Jan": [
                {
                    "id": "1",
                    "date_added": "2017-01-03 08:43:09"
                }
            ]
        },
        {
            "Feb": [
                {
                    "id": "4",
                    "date_added": "2017-02-04 10:53:44"
                }
            ]
        },
        {
            "Feb": [
                {
                    "id": "2",
                    "date_added": "2017-02-12 08:59:15"
                }
            ]
        }
    ]
}

如您所见,我的代码返回单独的二月数组,但我想将两者都存储在二月数组中。我尝试了不同的逻辑,但仍然面临同样的问题。

【问题讨论】:

  • 你可以改为$Res[] = array($alpha_month=>array($Data)); $Res[$alpha_month][] = $Data;
  • @Tyralcori 您为我提供了非常快速的解决方案和指导 +1。但由于要点较少,我无法对您的评论投赞成票
  • 我在“答案”中对所有内容进行了更详细的解释。我很高兴我能提供帮助。如果您需要更多信息,请随时联系。

标签: php mysql arrays json


【解决方案1】:

对我上面的简短评论更详细一点:

取而代之的是 $Res[] = array($alpha_month=>array($Data));你可以做 $Res[$alpha_month][] = $Data;

目前,您正在此 while 循环中获取所有结果元组,这是准确且可以的。但是,如果您想将某些结果“分组”到一个数组中,一种方法是:

$Res[$alpha_month][] = $Data;

使用此代码,您可以在 $Res 数组中“推送”结果 ($Data)。重要的部分是与新结构相关的第一个数组层$Res[$alpha_month]:

array('JAN', 'FEB', ...);

第二个[] 声明第一层,在这种情况下,它是您的月份组,另一个数组。您可能会通过第一次推送每个月的结果来获得PHP WARNINGS,因为$Res[$alpha_month][] 会导致您的数组中出现两级声明。

在第一个声明中,如前所述,您将所有组/月推入数组!但同时,php 期望第一个迭代也是一个数组:($Res[$alpha_month][])

所以干净的解决方案如下:

if(!isset($Res[$alpha_month])){
    $Res[$alpha_month] = array(); // You can also use []; instead array();
}
$Res[$alpha_month][] = $Data;

使用该 sn-p,您首先检查 $Res[$alpha_month] 是否存在 - 如果当前层不可用,它还会声明一个数组。

【讨论】:

    【解决方案2】:

    你可以试试

    $Res[$alpha_month][] = $data;
    

    这只会在您的数组中添加一个该月的条目,您也不再需要if(in_array($array_date,$month))

    【讨论】:

      猜你喜欢
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 2018-11-08
      • 2012-01-12
      • 1970-01-01
      相关资源
      最近更新 更多