重新定义数组结构的快速方法

时间:2014-11-13 17:05:30

标签: php arrays codeigniter activerecord

我有一个看起来像这样的数组:

    Array (
       [0] => Array
          (
              [id] => 1
              [day] => 12
              [month] => 10
              [year] => 2014
              [event_title] => numbwe1
              [event] => trip to this place unknown
          )

    [1] => Array
        (
            [id] => 2
            [day] => 16
            [month] => 10
            [year] => 2014
            [event_title] => number2
            [event] => trip to this other place unknown
        )
    ) 

我想让它看起来像这样

Array (
    [2014] => Array (
        [10] => Array (
            [1] => Array(
                [0] => Array(
                [event_title] = numbwe1
                [event] = trip to this place unknown
                )
            )

            [2] => Array(
                [0] => Array(
                [event_title] = number2
                [event] = trip to this other place unknown
                )
            )
        )
    )
)

我不知道是不是因为它已经晚了,或者它很复杂,但我无法理解它。任何人都有任何想法。

目的是我希望能够根据年份=>选择所有事件。 month => date =>

EG。 $ events [2014]给出了今年的所有活动。

$ events [2014] [11]在本月发布了所有活动。

$ events [2014] [11] [13]今天发布了所有活动。

也欢迎其他解决方案。

2 个答案:

答案 0 :(得分:2)

$newArray = array();
foreach ($array as $a) {
    $year = $a['year'];
    $month = $a['month'];
    $day = $a['day'];
    if (!isset($newArray[$year])) $newArray[$year] = array();
    if (!isset($newArray[$year][$month])) $newArray[$year][$month] = array();
    if (!isset($newArray[$year][$month][$day])) $newArray[$year][$month][$day] = array();
    $newArray[$year][$month][$day][] = $a; // No sense stripping out useful information
}

答案 1 :(得分:1)

这应该可行。警告:UNTESTED

function createDateSortableArray($array) {
    $sortableArray = [];
    foreach ($array as entry) {
        $year = $entry['year'];
        $month = $entry['month'];
        $daty = $entry['day'];
        if (!isset($sortableArray[$year])) {
            $sorableArray[$year] = [];
        }

        if (!isset($sortableArray[$year][$month])) {
            $sortableArray[$year][$month] = [];
        }

        if (!isset($sortableArray[$year][$month][$day]) {
            $sortableArray[$year][$month][$day] = [];
        }

        $sortableArray[$year][$month][$day][] = array(
            'event_title' => $entry['event_title'],
            'event' => $entry['event']
        );
    }

    return $sortableArray;
}