PHP sort multidimensional array by date - php

I'm having a problem. I have a multidimensional array, that looks like this:
Array ( [0] =>
Array (
[0] => Testguy2's post.
[1] => testguy2
[2] => 2013-04-03
)
[1] => Array (
[0] => Testguy's post.
[1] => testguy
[2] => 2013-04-07
)
);
I want to sort the posts from the newest date to the oldest date, so it looks like this:
Array ( [1] => Array (
[0] => Testguy's post.
[1] => testguy
[2] => 2013-04-07
)
[0] => Array (
[0] => Testguy2's post.
[1] => testguy2
[2] => 2013-04-03
)
);
How do I sort it?

function cmp($a, $b){
$a = strtotime($a[2]);
$b = strtotime($b[2]);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
usort($array, "cmp");
Or for >= PHP 7
usort($array, function($a, $b){
return strtotime($a[2]) <=> strtotime($b[2]);
});

You can do it using usort with a Closure :
usort($array, function($a, $b) {
$a = strtotime($a[2]);
$b = strtotime($b[2]);
return (($a == $b) ? (0) : (($a > $b) ? (1) : (-1)));
});

I'm just stepping away from my desk for the day so I can't offer specifics. But here's a good place to get started that includes examples: array_multisort

$dates = array();
foreach($a AS $val){
$dates[] = strtotime($val[2]);
}
array_multisort($dates, SORT_ASC, $a);

Related

Sorting a multi-dimensional Array by value

I have this array and I want to sort it (ASC)?
$stand_array[$player_name][$player_points] = $player_rank;
print_r
Array
(
[Player1] => Array
(
[50] => 5.7
)
[Player2] => Array
(
[40] => 4.2
)
[Player3] => Array
(
[30] => 3.7
)
[Player4] => Array
(
[20] => 2.3
)
[Player5] => Array
(
[10 => 1.5
)
[Player6] => Array
(
[60] => 6.3
)
)
Would you like to help me to solve this array on $player_rank (ASC)?
NB: I tried this function, but it did not work:
function sortByOrder($a, $b) {
return $a[$player_rank] - $b[$player_rank];
}
usort($myArray, 'sortByOrder');
The variable $player_rank is not visible from the sortByOrder function scope. Also, the indexes is different in each player array, so you need to access it like this:
function sortByOrder($a, $b)
{
$a = end($a);
$b = end($b);
if ($a == $b)
{
return 0;
}
return ($a < $b) ? -1 : 1;
}
usort($myArray, 'sortByOrder');
And if you want to save keys in $myArray then you must use the uasort function instead of usort.

Sort a multi array by one organ

I have a multi array that look like that:
Array (
[0] => Array(
[0] = Number;
),
[1] => Array(
[0] = Number;
)
)
And I want to sort it by the "Number" organ
For exmaple if I have:
Array (
[0] => Array(
[0] = 2;
),
[1] => Array(
[0] = 1;
)
)
I want to get:
Array (
[0] => Array(
[0] = 1;
),
[1] => Array(
[0] = 2;
)
)
I have more content in this arrays, I just wrote what need to be sort
How can I do that?
try:
Before PHP 5.3
function cmp($a, $b)
{
if ($a[0] == $b[0]) {
return 0;
}
return ($a[0] < $b[0]) ? -1 : 1;
}
usort($array, "cmp");
Updated for PHP 5.3
usort($myArray, function($a, $b) {
if ($a[0] == $b[0]) {
return 0;
}
return ($a[0] < $b[0]) ? -1 : 1;
});

Sort array numeric before string?

I can't sort my array so that numbers comes before - (hyphen).
My array today:
Array
(
[-] => Test
[0] => Test
[1] => Test
[2] => Test
)
The order I want:
Array
(
[0] => Test
[1] => Test
[2] => Test
[-] => Test
)
I have searched both here and on Google. But found no answers. I have tried experimenting with ksort() and usort(), but without success.
You could create your own compare function with uksort which handels such special cases.
uksort($a, function($a, $b) {
if (is_numeric($a) && is_numeric($b)) return $a - $b;
else if (is_numeric($a)) return -1;
else if (is_numeric($b)) return 1;
return strcmp($a, $b);
});
Use natural order sorting function
natsort()
example:
$arr = ['_', 6, 3, 5];
natsort($arr);
print_r($arr);
output:
Array
(
[2] => 3
[3] => 5
[1] => 6
[0] => _
)
If you want to sort by keys then you can use ksort() function with flag SORT_NATURAL ksort($arr, SORT_NATURAL);
example:
$arr = [
'_' => 'test',
6 => 'test',
3 => 'test',
5 => 'test'
];
ksort($arr, SORT_NATURAL);
function check($x, $y){
if(is_numeric($x) && !is_numeric($y))
return 1;
else if(!is_numeric($x) && is_numeric($y))
return -1;
else
return ($x < $y) ? -1 : 1;
}
$array = array("-", "1", "2", "3");
usort ( $array , 'check' );

How to get the difference of specific data types encoded into arrays

How to get the difference of arrays containing data-types?
First array:
Array
(
[0] => Array
(
[ID] => 21323154
[NAME] => Name_2
[PREVIEW_TEXT] => Text_2
)
)
Second array:
Array
(
[0] => Array
(
[ID] => 543547564
[NAME] => Name_1
[PREVIEW_TEXT] => Text_1
)
[1] => Array
(
[ID] => 222213322
[NAME] => Name_2
[PREVIEW_TEXT] => Text_2
)
[2] => Array
(
[ID] => 333876833
[NAME] => Name_3
[PREVIEW_TEXT] => Text_3
)
)
The result should be an array:
Array
(
[0] => Array
(
[ID] => 543547564
[NAME] => Name_1
[PREVIEW_TEXT] => Text_1
)
[1] => Array
(
[ID] => 333876833
[NAME] => Name_3
[PREVIEW_TEXT] => Text_3
)
)
I tried different options, but they all return the result found the difference, i.e. the first array.
I have a different ID
Just try with:
$output = array_udiff($arraySecond, $arrayFirst, function($a, $b){
return strcmp($a['NAME'], $b['NAME']);;
});
Output:
array(2) {
[0] =>
array(3) {
'ID' =>
int(543547564)
'NAME' =>
string(6) "Name_1"
'PREVIEW_TEXT' =>
string(6) "Text_1"
}
[2] =>
array(3) {
'ID' =>
int(333876833)
'NAME' =>
string(6) "Name_3"
'PREVIEW_TEXT' =>
string(6) "Text_3"
}
}
If both arrays are large, array_diff will be very inefficient, because it compares each element of the first array with each element of the second. A faster solution is to split the process into two steps: first, generate a set of keys to remove:
$remove = array();
foreach($firstArray as $item)
$remove[$item['name']] = 1;
and then iterate over the second array and add "good" items to the result:
$result = array();
foreach($secondArray as $item)
if(!isset($remove[$item['name']]))
$result []= $item;
This will give you linear performance, while array_diff is quadratic.
Diff both arrays against the field (column) you want to, give back only those entries then (thanks to keys):
$col = 'NAME';
$diff = array_intersect_key($b, array_diff(array_column($b, $col), array_column($a, $col)));
print_r($diff);
If you prefer to have this less quadratic but linear, you can also solve it via iteration (inspired by georg's answer but using array_column() again):
$filtered = function ($col, $a, $b) {
return iterator_to_array(call_user_func(function () use ($col, $a, $b) {
$coled = array_flip(array_column($a, $col));
foreach ($b as $bk => $bv) if (!isset($coled[$bv[$col]])) yield $bk => $bv;
}));
};
print_r($filtered('NAME', $a, $b));
With $a and $b as outlined, you will get the following result for both examples:
Array
(
[0] => Array
(
[ID] => 543547564
[NAME] => Name_1
[PREVIEW_TEXT] => Text_1
)
[2] => Array
(
[ID] => 333876833
[NAME] => Name_3
[PREVIEW_TEXT] => Text_3
)
)
// 1.) - diff against column, intersect keys
$filtered = function($col, $a, $b) {
return array_intersect_key($b, array_diff(array_column($b, $col), array_column($a, $col)));
};
// 2.) - iterate and take only unset by column
$filtered = function ($col, $a, $b) {
return iterator_to_array(call_user_func(function () use ($col, $a, $b) {
$coled = array_flip(array_column($a, $col));
foreach ($b as $bk => $bv) if (!isset($coled[$bv[$col]])) yield $bk => $bv;
}));
};
// 3.) - array_udiff against column
$filtered = function($col, $a, $b) {
return array_udiff($b, $a, function ($a, $b) use ($col) {
return strcmp($a[$col], $b[$col]);
});
};
Usage:
print_r($filtered('NAME', $a, $b));
Where $a is the array containing the elements to remove from the $b array. So $a is the first array of the question and $b is the second array of the question.

How to sort nested PHP array

Can anyone tell me how to sort an array by key?
I want to sort this array by price.
this is my input array format
Array
(
[0] => Array
(
[house_data] => Array
(
[id] => 532
[max_person] => 8
[max_bedrooms] => 4
)
[image] => uploads/123.jpg
[price] => 1950
)
[1] => Array
(
[house_data] => Array
(
[id] => 531
[max_person] => 8
[max_bedrooms] => 5
)
[image] => uploads/1234.jpg
[price] => 1495
)
}
Try usort (http://php.net/manual/en/function.usort.php)
You should have something like:
function cmp($a, $b)
{
if ($a['price'] == $b['price']) {
return 0;
}
return ($a['price'] < $b['price']) ? -1 : 1;
}
usort($table, "cmp");
For making it one dimensional use serialize($array) function , it goes like this :$a = array() ; //your multidimensional array$b = array(); //output arrayforeach ($a as $key=>$value){ $b[] = serialize($value);}echo $b ;
Use the array_multisort() function for multidimensional array sorting.

Categories