phparrayssortingarray-merge

Merge two 2d arrays then sort rows by date value which may been found in one of two columns


I have two arrays.

$array1 = [
    [
        'date' => '2012-01-10',
        'result' => 65,
        'name' => 'Les océans',
    ],
    [
        'date' => '2012-01-11',
        'result' => 75,
        'name' => 'Les mers',
    ],
    [
        'date' => '2012-01-13',
        'result' => 66,
        'name' => 'Les continents',
        'type' => 'Scores',
    ]
];

$array2 = [
    [
        'date_end' => '2012-01-12',
        'result' => 60,
        'name' => 'Step#1',
        'type' => 'Summary',
    ]
];

And I want this for my final result:

Array
(
    [0] => Array
    (
        [date] => 2012-01-10
        [result] => 65
        [name] => Les océans
    )
    [1] => Array
    (
        [date] => 2012-01-11
        [result] => 75
        [name] => Les mers
    )
    [2] => Array
    (
        [date_end] => 2012-01-12
        [result] => 60
        [name] => Step#1
        [type] => Summary
    )
    [3] => Array
    (
        [date] => 2012-01-13
        [result] => 66
        [name] => Les continents
        [type] => Scores
    )
)

I need to merge my first array with the second then I want to order this new array by date.


Solution

  • array_merge and usort is your friend.

    function cmp($a, $b){
        $ad = strtotime($a['date']);
        $bd = strtotime($b['date']);
        return ($ad-$bd);
    }
    $arr = array_merge($array1, $array2);
    usort($arr, 'cmp');
    

    Result: (online demo)

    Warning: Undefined array key "date"
    
    Deprecated: strtotime(): Passing null to parameter #1 ($datetime) of type string is deprecated
    
    Warning: Undefined array key "date"
    
    Deprecated: strtotime(): Passing null to parameter #1 ($datetime) of type string is deprecated
    
    Warning: Undefined array key "date"
    
    Deprecated: strtotime(): Passing null to parameter #1 ($datetime) of type string is deprecated
    array (
      0 => 
      array (
        'date_end' => '2012-01-12',
        'result' => 60,
        'name' => 'Step#1',
        'type' => 'Summary',
      ),
      1 => 
      array (
        'date' => '2012-01-10',
        'result' => 65,
        'name' => 'Les océans',
      ),
      2 => 
      array (
        'date' => '2012-01-11',
        'result' => 75,
        'name' => 'Les mers',
      ),
      3 => 
      array (
        'date' => '2012-01-13',
        'result' => 66,
        'name' => 'Les continents',
        'type' => 'Scores',
      ),
    )