1

我得到了这种格式的数组。

   Date            Employee               Notes
   2013-03-08        ABC                 Notes of ABC on 08-03-2013
   2013-03-08        PQR                 Notes of PQR on 08-03-2013
   2013-03-08        XYZ                 Notes of XYZ on 08-03-2013
   2013-03-09        ABC                 Notes of ABC on 09-03-2013
   2013-03-09        PQR                 Notes of PQR on 09-03-2013
   2013-03-09        XYZ                 Notes of XYZ on 09-03-2013

我想要这种格式的结果数组

 Date            Employee               Notes
 2013-03-08        ABC                 Notes of ABC on 08-03-2013
                   PQR                 Notes of PQR on 08-03-2013
                   XYZ                 Notes of XYZ on 08-03-2013
 2013-03-09        ABC                 Notes of ABC on 09-03-2013
                   PQR                 Notes of PQR on 09-03-2013
                   XYZ                 Notes of XYZ on 09-03-2013

那么我怎样才能编写我的 php 代码来获得这样的结果呢?这是一个二维数组,我使用 foreach 循环来显示这样的。

有人可以帮我吗?

4

2 回答 2

1

您只需要迭代初始数组,并将当前日期存储在 var 中。在下一个日期不变的情况下,您将子数据存储在同一个子条目中。

假设你有

$initial = array(
    array('2013-03-08','ABC','Notes of ABC on 08-03-2013'),
    array('2013-03-08','PQR','Notes of PQR on 08-03-2013'),
    array('2013-03-08','XYZ','Notes of XYZ on 08-03-2013'),
    array('2013-03-09','ABC','Notes of ABC on 09-03-2013'),
    array('2013-03-09','PQR','Notes of PQR on 09-03-2013'),
    array('2013-03-09','XYZ','Notes of XYZ on 09-03-2013')
)

你可以让你的新数组像

$final = array();
$currentDate = false;
foreach($initial as $index => $subArray)
{
    if ($currentDate === false || $currentDate != $subArray[0])
    {
        $currentDate = $subArray[0];
        $final[$currentDate] = array();
    }

    $final[$currentDate][] = array($subArray[1], $subArray[2]);
}
于 2013-03-13T04:46:44.563 回答
0

这将起作用:

$entries = array(
    array("Date" => "2013-03-08", "Employee" => "ABC", "Notes" => "Notes of ABC on 08-03-2013"),
    array("Date" => "2013-03-08", "Employee" => "PQR", "Notes" => "Notes of PQR on 08-03-2013"),
    array("Date" => "2013-03-08", "Employee" => "XYZ", "Notes" => "Notes of XYZ on 08-03-2013"),
    array("Date" => "2013-03-09", "Employee" => "ABC", "Notes" => "Notes of ABC on 09-03-2013"),
    array("Date" => "2013-03-09", "Employee" => "PQR", "Notes" => "Notes of PQR on 09-03-2013"),
    array("Date" => "2013-03-09", "Employee" => "XYZ", "Notes" => "Notes of XYZ on 09-03-2013")
);

$y = array();
foreach ($entries as $entry) {
    $date = $entry["Date"];
    if (!isset($y[$date])) $y[$date] = array();
    unset($entry["Date"]);
    $y[$date][] = $entry;
}

print_r($y);
于 2013-03-13T04:43:56.847 回答