按php数组排序

Gil*_*dar 5 php sorting date

我需要按照getNotifications函数中值'start_date'的DESC顺序对通知数组进行排序:

$posts_id_arr = getPoststIds($conn);

foreach ($posts_id_arr as $key => $val) {
  $total_arr[$key] = [
    'notification' => getNotifications($val['post_id'], $user_id, $conn)
  ];
}

$response_array = array('data' => $total_arr, 'more things' => $more_array);
echo json_encode($response_array);
Run Code Online (Sandbox Code Playgroud)

现在,由于foreach循环,订单是通过邮递ID进行的。

data {
       notification: 
      [
       {
        post_id: “1",
        start_date: "2016-10-10 08:00:00",
       },
       {
        post_id: “1",
        start_date: "2016-10-10 12:00:00",
       }
    ],
     notification:
      [
        post_id: “2",
        start_date: "2016-10-10 09:00:00",
       },
       {
        post_id: “2",
        start_date: "2016-10-10 13:00:00",
       }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我需要是1:08:00,2:09:00,1:12:00,2:13:00

Nar*_*r P 0

如果您想使用内部数组进行排序,您可以更好地选择该usort()方法。

\n\n

usort \xe2\x80\x94 使用用户定义的比较函数按值对数组进行排序

\n\n

该函数将使用用户提供的比较函数按数组的值对数组进行排序。如果您希望排序的数组需要按某些重要标准进行排序,则应使用此函数。

\n\n
<?php\nfunction cmp($a, $b)\n{\n    return strcmp($a["fruit"], $b["fruit"]);\n}\n\n$fruits[0]["fruit"] = "lemons";\n$fruits[1]["fruit"] = "apples";\n$fruits[2]["fruit"] = "grapes";\n\nusort($fruits, "cmp");\n\nwhile (list($key, $value) = each($fruits)) {\n    echo "\\$fruits[$key]: " . $value["fruit"] . "\\n";\n}\n?>\n
Run Code Online (Sandbox Code Playgroud)\n\n

对多维数组进行排序时,$a包含$b对数组第一个索引的引用。

\n\n

上面的例子将输出:

\n\n
$fruits[0]: apples\n$fruits[1]: grapes\n$fruits[2]: lemons\n
Run Code Online (Sandbox Code Playgroud)\n\n

替代解决方案:

\n\n

您可以尝试,array_multisort()因为它会根据您需要的顺序对数组进行排序。

\n\n
$arr  = your array;\n$sort = array();\nforeach($arr as $k=>$v) {\n    $sort[\'field\'][$k] = $v[\'field\'];\n}\n\narray_multisort($sort[\'field\'], SORT_DESC, $arr);\n\necho "<pre>";\nprint_r($arr);\n
Run Code Online (Sandbox Code Playgroud)\n