Search code examples
phparraysarray-mergepreg-grep

Array merge combination with foreach


What array management operations are needed? So, there are two arrays and I want to combine the following way:

$arr

Array
(
    [0] => 2015-08-16 22:12:04
    [1] => 2015-08-16 13:20:17
    [2] => 2015-08-16 11:45:47
    [3] => 2015-08-16 02:35:12
    [4] => 2015-08-15 19:05:02
    [5] => 2015-08-15 17:35:12
    [6] => 2015-08-15 09:02:25
    [7] => 2015-08-15 07:12:00
    [8] => 2015-08-14 22:12:04
    [9] => 2015-08-14 13:20:17
    [10] => 2015-08-14 11:45:47
)

other array ($arr2)

Array
(
    [2015-08-16 22:12:04] => 4.8
    [2015-08-16 13:20:17] => 5.8
    [2015-08-16 11:45:47] => 4.7
    [2015-08-16 02:35:12] => 2.8
    [2015-08-15 19:05:02] => 5.0
    [2015-08-15 17:35:12] => 3.0
    [2015-08-15 09:02:25] => 5.6
    [2015-08-15 07:12:00] => 4.0
    [2015-08-14 22:12:04] => 4.8
    [2015-08-14 13:20:17] => 5.8
)

I would like the following output: $arr3

Array
(
    2015-08-16 => Array 
        (
           [2015-08-16 22:12:04] => 4.8
           [2015-08-16 13:20:17] => 5.8
           [2015-08-16 11:45:47] => 4.7
           [2015-08-16 02:35:12] => 2.8
        )
    2015-08-15 => Array 
        (
           [2015-08-15 19:05:02] => 5.0
           [2015-08-15 17:35:12] => 3.0
           [2015-08-15 09:02:25] => 5.6
           [2015-08-15 07:12:00] => 4.0
        )
    2015-08-14 => Array 
        (
           [2015-08-14 22:12:04] => 4.8
           [2015-08-14 13:20:17] => 5.8
           [2015-08-14 11:45:26] => 4.4
        )

)

So far I got: (the whole is a for loop)

$ts = strtotime($year.'W'.$week.$i);
$thedates = date("Y-m-d", $ts);

$input = preg_quote($thedates, '~');
$input = str_replace("\-","-",$input);
$result = preg_grep('~' . $input . '~', $arr);

$a = array(
   $thedates=>$result,                      
);

Output:

Array
(
    [1439510400] => Array
        (
            [8] => 2015-08-14 22:12:04
            [9] => 2015-08-14 13:20:17
            [10] => 2015-08-14 11:45:47
            [11] => 2015-08-14 02:35:12
        )
)

Array
(
    [1439596800] => Array
        (
            [4] => 2015-08-15 19:05:02
            [5] => 2015-08-15 17:35:12
            [6] => 2015-08-15 09:02:25
            [7] => 2015-08-15 07:12:00
        )
)

Array
(
    [1439683200] => Array
        (
            [0] => 2015-08-16 22:12:04
            [1] => 2015-08-16 13:20:17
            [2] => 2015-08-16 11:45:47
            [3] => 2015-08-16 02:35:12
        )
)

Solution

  • A simple foreach loop will do what you want. Just explode() the key by the space, so you have date and time separated, e.g.

    <?php
    
        $result = [];
    
        foreach($arr2 as $k => $v){
            list($date, $time) = explode(" ", $k);
            $result[$date][$k] = $v;
        }
    
    ?>