Cedric Weatherly Cedric Weatherly - 1 year ago 100
PHP Question

Simple PHP Array Sorting by sub array key

Trying to sort the array below by "end" without the use of usort function, is there a simple way to do so?

$feature_event = array(
"title" => "Classic",
"date" => "October 28 - 30 2016",
"end" => strtotime("October 30, 2016")
"title" => "Ski Weekend",
"date" => "February 5-8, 2017",
"end" => strtotime("February 8, 2017")
"title" => "NBA Weekend",
"date" => "February 17-19, 2017",
"end" => strtotime("February 19, 2017")
"title" => "Fiesta",
"date" => "May 26-28, 2017",
"end" => strtotime("May 28, 2017")

I'm outputting the result via a foreach loop but want to limit to 3 results.

<?php foreach( array_slice($feature_event, 0, 3) as $event): ?>
<?php endforeach; ?>

Small explanation:
I'm trying to display images that are associated with an event. Each event has a specific end date. Once the end date is past, display the next image in the loop...but I want the array sorted by the end date. I understand a usort function would do the trick but I'm not that advance in coding. Is there a simple way of accomplishing sorting by "end" or would I need to do a usort. If needing a usort would I still need the forloop? Plz excuse my dumb question.


This array multisort solution

array_multisort(array_column($feature_event, 'end'), $feature_event);

sorts the way I'm needing it to but I would like to output the data based off the current date...I can't seem to create a conditional that works correctly...

within my forloop I have this conditional:

$now = strtotime("now");

<?php if($now <= $event["end"]) :?>
... code ...
<?php endif;?>

but it is only outputting 2 events....any ideas on what I'm doing wrong. This if is inside the foreachloop above.

Answer Source

Since the end values are timestamps, just extract those into an array and sort that, sorting the original array:

PHP < 5.5.0:

    array_map(function($v) { return $v['end']; }, $feature_event), $feature_event);

PHP >= 5.5.0:

array_multisort(array_column($feature_event, 'end'), $feature_event);

Or use SORT_DESC as the third parameter depending on which way you want to sort.

Then use your array_slice() to get the first or last 3 and loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download