Hey guys,
I have an array that I would like to sort.
array(2) { [0]=> array(1) { ["show_date_and_time"]=> string(15) "2026-8-17 12:00" } [1]=> array(1) { ["show_date_and_time"]=> string(16) "2021-12-17 12:00" } } array(2) { [0]=> array(1) { ["show_date_and_time"]=> string(15) "2018-1-18 12:03" } [1]=> array(1) { ["show_date_and_time"]=> string(15) "2017-4-26 16:00" } } array(2) { [0]=> array(1) { ["show_date_and_time"]=> string(15) "2015-9-17 14:00" } [1]=> array(1) { ["show_date_and_time"]=> string(15) "2025-7-17 18:30" } }
From the smallest date to the highest date using php… any point in the direct direction will be appreciated.
Does the data originate from a database query?
Yes. Sorry for the delayed reply (intenet issues). It is from a meta field in WordPress.
I am basically dumping the value there, e.g.
$x = get_meta...
var_dump($x);
It seems you’ve used/pasted the var_dump value.
I assume the structure of the array is similar to the one below:
$arr = array();
$arr[0] = array();
$arr[0][0]["show_date_and_time"] = "2026-8-17 12:00";
$arr[0][1]["show_date_and_time"] = "2021-12-17 12:00";
$arr[1] = array();
$arr[1][0]["show_date_and_time"] = "2018-1-18 12:03";
$arr[1][1]["show_date_and_time"] = "2017-4-26 16:00";
$arr[2] = array();
$arr[2][0]["show_date_and_time"] = "2015-9-17 14:00";
$arr[2][1]["show_date_and_time"] = "2025-7-17 18:30";
I don’t know the best solution for this, but it would be better to tone down the usage of the internal arrays by merging them:
$new_array = array();
foreach($arr as $array)
{
$new_array = array_merge($new_array, $array);
}
Then you can just use sort() method to sort the date.
sort($new_array);
Output
array(6) {
[0]=>
array(1) {
["show_date_and_time"]=>
string(15) "2015-9-17 14:00"
}
[1]=>
array(1) {
["show_date_and_time"]=>
string(15) "2017-4-26 16:00"
}
[2]=>
array(1) {
["show_date_and_time"]=>
string(15) "2018-1-18 12:03"
}
[3]=>
array(1) {
["show_date_and_time"]=>
string(16) "2021-12-17 12:00"
}
[4]=>
array(1) {
["show_date_and_time"]=>
string(15) "2025-7-17 18:30"
}
[5]=>
array(1) {
["show_date_and_time"]=>
string(15) "2026-8-17 12:00"
}
}
Note: Mind you, this does change the array structure from 2-depth to 1-depth if you want to reuse it.
If you want to get back the original structure of the array, you can use array_chunk.
$orig_array = array_chunk($new_array, 2);
system
Closed
6
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.