简体   繁体   中英

Creating an associative multidimensional array in PHP

I'm trying to create an array where the Month is the key and each key contains one or more dates within them. I start with an array that looks like $arr below. Sidenote: I do not control how the original array is structured as it comes from an API. I merely added the below $arr to illustrate and make it easier for people to understand and debug.

$arr = array(
    0 => array(
        'date' => '2020-12-07'
    ),
    1 => array(
        'date' => '2020-12-19'
    ),
    2 => array(
        'date' => '2021-01-03'
    ),
    3 => array(
        'date' => '2020-01-18'
    )
);

Because I need to display the dates differently than this, I need to construct an array which contains the Month name and a formated date:

$sorted = array(); // This is the array I will return later.
foreach ( $arr as $day ) {
    setlocale(LC_TIME, 'sv_SE');
    $month          = strftime( '%B',   strtotime( $day['date'] ) );
    $display_date   = trim( strftime( '%e %b', strtotime( $day['date'] ) ) );
}

Everything I've tried doing here so far has failed. I can't even remember all methods to be honest. The last I tried was this (within the foreach()):

array_push($sorted, array(
    $month => $display_date
));

The var_dump() of that, generated an enumerated array:

    array (size=4)
    0 => 
        array (size=1)
        'December' => string '7 Dec' (length=5)
    1 => 
        array (size=1)
        'December' => string '19 Dec' (length=6)
    2 => 
        array (size=1)
        'Januari' => string '3 Jan' (length=5)
    3 => 
        array (size=1)
        'Januari' => string '18 Jan' (length=6)

What I'm trying to achieve is this:

All $display_date 's should sit under its $month key. The $month key must be unique and contain all dates for that month.

Thankful for any help that gets me in the right direction here because I feel like I'm doing something fundamentally wrong.

You are appending new array with month and date every loop, replace array_push() with $sorted[$month][] = $display_date;

foreach ( $arr as $day ) {
    setlocale(LC_TIME, 'sv_SE');
    $month          = strftime( '%B',   strtotime( $day['date'] ) );
    $display_date   = trim( strftime( '%e %b', strtotime( $day['date'] ) ) );

    $sorted[$month][] = $display_date;
}

print_r($sorted);

Output:

Array
(
    [december] => Array
        (
            [0] => 7 dec
            [1] => 19 dec
        )

    [januari] => Array
        (
            [0] => 3 jan
            [1] => 18 jan
        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM