-1

I would like to make an array like below.

The key should be day. The value should be string weekday name.

$array = [
    1 =>['mon'],
    2 =>['tue'],
    3 =>['wed']
];

However $day (key) can't seem to be recognised.

CODE is

//$i is the first day of a specific month. this sample is 2022-11-01
    for($j = $i ; (int)date_create($j)->format('w') < 6 ; $j++){
        print_r("くj");
        print_r($j);
        
        $day = date_create($j)->format('j');
        print_r("day");
        print_r($day);
        $dailyArray  = array_merge($dailyArray ,array( $day => mb_strtolower(date_create($j)->format('D'))));//
        print_r("THE RESULT!!");
        print_r($dailyArray);

result(November/2022) is

THE RESULT!! day4

Array
(
    [0] => Tue
    [1] => Wed
    [2] => Thu
    [3] => Fri
)

It's not the question, but it can't set (int)date_create($j)->format('w') <= 6 . How can I do the loop until sat?

user14232549
  • 405
  • 4
  • 17
  • Can you simplify your question a bit more with a minimum reproducible example? This is super confusing to me right now. – nice_dev May 25 '22 at 04:59
  • Does [this](https://stackoverflow.com/questions/3292044/php-merge-two-arrays-while-keeping-keys-instead-of-reindexing) answer your question? – enricog May 25 '22 at 05:11

1 Answers1

0

The following script was based on your code basically and it will print out the result as expected, till Saturday

$dailyArray  = array();
$d = 1;
while($d < 6 ){
    $j = implode("-", array(2022, 11, str_pad($d, 2, '0', STR_PAD_LEFT)));
    print_r("くj");
    print_r($j);
    $day = date_create($j)->format('j');
    print_r("day");
    print_r($day);
    $dailyArray  = array_merge($dailyArray , array( $day => strtolower(date_create($j)->format('D'))));
    $d++;
}
print_r("<p>THE RESULT!!");
print_r($dailyArray);

It should print out

THE RESULT!!Array ( [0] => tue [1] => wed [2] => thu [3] => fri [4] => sat )

Actually, if (int)date_create($j)->format('w') < 6 is preferred, a shorter version could be

$d = 1;
$j = implode("-", array(2022, 11, str_pad($d, 2, '0', STR_PAD_LEFT)));
while((int)date_create($j)->format('w') < 6 ){
    $j = implode("-", array(2022, 11, str_pad($d, 2, '0', STR_PAD_LEFT)));
    $dailyArray[$d] = strtolower(date_create($j)->format('D'));
    $d++;
}

It printed out:

THE RESULT!!Array ( [1] => tue [2] => wed [3] => thu [4] => fri [5] => sat )
ild flue
  • 1,323
  • 8
  • 9