简体   繁体   中英

Unable to sort multi-dimensional array by date in PHP

I am currently trying to sort a multi-dimensional array by a due date in PHP, but the sort is unsuccessful. I've tried applying several of the solutions here, but have had no luck. Can someone please advise on a proper solution for the code below?

function getTasksTeam($user) {

    $master = array();
    $master["record"] = array();


    $teamArray = array();
    $teams = mysql_query("SELECT * FROM users WHERE _id = '$user'") or die(mysql_error());
    if (mysql_num_rows($teams) > 0) {
                        while(($row =  mysql_fetch_assoc($teams))) { 
                            $teamArray = explode(':', $row["TEAM"]);

                        }
    }

    for ($i = 0;$i < count($teamArray);$i++) {
        $teamId = $teamArray[$i];

        $query = mysql_query("SELECT * FROM tasks WHERE RESPONSIBLE_TYPE = '0' AND RESPONSIBLE = '$teamId' AND STATUS <> 3") or die(mysql_error());
        if (mysql_num_rows($query) > 0) {
            while (($row = mysql_fetch_assoc($query))) {
                    $record = array();
                    $record["id"] = $row["_id"];
                    $record["task"] = $row["TASK"];
                    $record["part_number"] = $row["PART_NUMBER"];
                    $record["due"] = $row["DATE_DUE"];
                    $record["responsible"] = $row["RESPONSIBLE"];
                    $record["status"] = $row["STATUS"];
                    array_push($master["record"], $record);

            }
        }
    }

    usort($master["record"], 'date_sort');

    $master["success"] = 1;
    header('Content-type: application/json');
    echo json_encode($master);

 }

 function date_sort($a, $b) {
    return strcmp($a['due'], $b['due']); 
 }

You can use usort and strtotime like this:

usort($master["record"], function($a, $b) {
    return strtotime($a['due']) - strtotime($b['due']);
});

I hope this will help you.

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