如何得到这种格式的二维数组



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

   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循环来显示。

谁能帮帮我?

您只需要迭代初始数组,并将当前日期存储在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]);
}

可以:

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

相关内容

  • 没有找到相关文章