Combine two array and order this new array by date

后端 未结 3 1744
时光说笑
时光说笑 2021-02-19 13:58

. I have two array

First One

 Array
    (
        [0] => Array
            (
                [date] => 2012-01-10
                [result] => 65         


        
相关标签:
3条回答
  • 2021-02-19 14:04

    array_merge your arrays and then use the following code as an example of how you can sort it.

    function sortDate($val1, $val2)
    {
        if ($val1['date'] == $val2['date']) {
            return 0;
        }
    
        return (strtotime($val1['date']) < strtotime($val2['date'])) ? -1 : 1;
    }
    
    $array = array(
        array('date' => '2012-01-10'),
        array('date' => '2011-01-10'),
        array('date' => '2012-01-01')
    );
    
    usort($array, "sortDate");
    print_r($array);
    
    0 讨论(0)
  • 2021-02-19 14:25

    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');
    
    0 讨论(0)
  • 2021-02-19 14:28

    Use array_merge() to combine the arrays, and then use sort to sort() to sort them, very simple. Would you like an example?

    This should sort it for you:

    function dateSort($a,$b){
        $dateA = strtotime($a['date']);
        $dateB = strtotime($b['date']);
        return ($dateA-$dateB);
    }
    
    $arrayOne = array(
        array(
            'date'      => '2012-01-10',
            'result '   => 65,
            'name'      => 'Les oc&eacute;ans'
        ),
        array(
            'date'      => '2012-01-11',
            'result '   => 75,
            'name'      => 'Les mers'
        ),
        array(
            'date'      => '2012-01-13',
            'result '   => 66,
            'name'      => 'Les continents',
            'type'      => 'Scores'
        )
    );
    
    $arrayTwo = array(
        array(
            'date'      => '2012-01-12',
            'result '   => 60,
            'name'      => 'Step#1',
            'type'      => 'Summary'
        )
    );
    
    // Merge the arrays
    $combinedArray = array_merge($arrayOne,$arrayTwo);
    
    // Sort the array using the call back function
    usort($combinedArray, 'dateSort');
    
    0 讨论(0)
提交回复
热议问题