如何以这种格式获得二维数组?

时间:2013-03-13 04:36:59

标签: php javascript jquery multidimensional-array

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

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

有人可以帮助我吗?

2 个答案:

答案 0 :(得分: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]);
}

答案 1 :(得分: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);