Sort by php array

I need to sort the notification array using the "start_date" DESC order value from the getNotifications function:

$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);

right now the order on the id column due to the foreach loop.

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",
       }
    ]
}

And I need it to be 1: 08:00, 2: 09:00, 1:12:00, 2: 13:00

+4
source share
4 answers

If you want to sort with an internal array, it is better to choose a method usort().

usort - sort an array by values ​​using a custom comparison function

, . , , , .

<?php
function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

while (list($key, $value) = each($fruits)) {
    echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>

$a $b .

:

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

:

array_multisort(), , .

$arr  = your array;
$sort = array();
foreach($arr as $k=>$v) {
    $sort['field'][$k] = $v['field'];
}

array_multisort($sort['field'], SORT_DESC, $arr);

echo "<pre>";
print_r($arr);
0

foreach.

. .

foreach ($points as $key => $val) {
    $time[$key] = $val[0];
}

array_multisort($time, SORT_ASC, $points);

, array_multisort. , $time , $points $time. Array_multisort foreach, , .

0

uasort. strcmp - , .

function sort_by_date($a, $b) {
  return strcmp($a->start_date, $b->start_date);
}

$sorted_posts = uasort($total_arr->notification, 'sort_by_date');

$response_array = array('data' => $sorted_posts, 'more things' => $more_array);
0

:

1) :

foreach ($total_arr['notification'] as $vals) {
    $temp_dates[] = $vals['start_date'];
}

2) temp arsort():

arsort($temp_dates);

3) array_filter() :

$i = 0;
foreach ($total_arr['notification'] as $vals) {
    $res['notification'][] = array_filter($vals, function($val) {
        return $val['start_date'] == $temp_dates[$i];
    });
    $i++;
}

$response_array = array('data' => $res, 'more things' => $more_array);

Note. Not sure if it works with duplicate start_dates.

0
source

Source: https://habr.com/ru/post/1657245/


All Articles