Sorting a non-associative, multidimensional array - php

I found lots of info about sorting associative arrays but little about sorting non-associative ones. My array is structured/populated this way:
$my_array = array();
$my_array[0][0] = 'whatever3';
$my_array[0][1] = 3
$my_array[1][0] = 'whatever2';
$my_array[1][1] = 2
$my_array[2][0] = 'whatever1';
$my_array[2][1] = 1
I want to sort it by the second value to get:
$my_array[0][0] = 'whatever1';
$my_array[0][1] = 1;
$my_array[1][0] = 'whatever2';
$my_array[1][1] = 2;
$my_array[2][0] = 'whatever3';
$my_array[2][1] = 3;
How can this be achieved considering my array isn't associative?

What about:
usort($combined, function ($a, $b) { return $a[1] - $b[1]; });
With usort you provide a custom comparison function that must return:
0, if the elements must be considered equal.
a negative number, if the first element must be considered smaller than the second one.
a positive number, if the first element must be considered greater than the second one.
In this case, we choose to compare the second element of each item of $combined array.

Related

Sorting a two dimensions array using second level values

I have a 2 dimensions array and need to sort it according to some of the second dimension values.
I tried using uksort, but it doesn't work:
$arr = array();
$arr[] = array('name'=>'test1', 'age'=>25);
$arr[] = array('name'=>'test2', 'age'=>22);
$arr[] = array('name'=>'test3', 'age'=>23);
$arr[] = array('name'=>'test4', 'age'=>29);
uksort($arr, "cmp");
print_r($arr);
function cmp($a, $b) {
if ($a['age']==$b['age']) return 0;
return ($a['age'] < $b['age']) ? -1 : 1;
}
Can anyone spot what am I doing wrong?
I think you are looking for uasort().
uksort() will order your array by keys, but you want to sort the arrays by their value.
uksort
Sort an array by keys using a user-defined comparison function
Sorting array by keys means that you take value of a key (in your case it is the same string age for all subarrays). And you sort by value.
So usort is enough - fiddle.

Find array element with greatest or smallest sub-array element value

Element 1 of the following array represents the element with the greatest x value, and element 2 represents the element with the smallest x element.
Without looping over each array using PHP code, how can the index of the element with the greatest and smallest x be determined?
$array = [
['x'=>5,'y'=>3],
['x'=>9,'y'=>3],
['x'=>3,'y'=>3],
['x'=>7,'y'=>3]
];
Extract the x column and compute it:
$x = array_column($array, 'x');
$min = min($x);
$max = max($x);
Or, as JustOnUnderMillions points out:
list($min, $max) = [min($x=array_column($array, 'x')), max($x)];
To get the index of the array containing that value, just use array_search(). It will return the first key if there are multiple identical values:
$x = array_column($array, 'x');
$min = array_search(min($x), $x, true);
$max = array_search(max($x), $x, true);
PHP >= 5.5.0 needed for array_column() or use the PHP Implementation of array_column()

PHP sort array of associative arrays by element size / string size

Is there a way to sort an array of associative arrays by the length of one of the elements? What I am trying to do is order the arrays by the largest to smallest description length.
$some_array = [];
$some_array[0] = ['name'=>'a name','description'=>'a description'];
$some_array[1] = ['name'=>'a name1','description'=>'a description 1'];
$some_array[2] = ['name'=>'a name2','description'=>'a description two for the third array element'];
$some_array[3] = ['name'=>'a name3','description'=>'a description three'];
With the above example $some_array[2] should come first followed by 3 then 1 then 0.
PHP >= 5.5.0 needed for array_column:
array_multisort(array_map('strlen', array_column($some_array, 'description')),
SORT_DESC,
$some_array);
Use usortto sort arrays based on custom parameters.
usort($array, function($a, $b) {
return strlen($b['description']) - strlen($a['description']);
});
var_dump($array)

Sort 2-dimensional array by elements of inner arrays

I have an Array with 8 arrays inside.
It looks like this:
[[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...]]
Each of this inner arrays has as its first element a number. Now I want to receive the element of the outer array with the biggest number as first element.
How do I do that?
Thank you very much.
You can define any sorting algorithm by using PHP's usort()
usort($array, function($a, $b) {
return $a[0] > $b[0];
});
This will sort your array, in place, such that the first element will have the largest number as it's first element.
It's not necessary (and is much more expensive) to sort the entire array. Something like this would work:
// initially, regard the first element as the largest
$element = $array[0];
$greatest = $array[0][0];
$length = count($array);
// compare the first value of each array against $greatest, swapping $element if it's larger
for($i = 1; $i < $length; $i++) { // N.B. start with second element
if($array[$i][0] > $greatest) {
$element = $array[$i];
}
}
// $element is now the element with the biggest first value
Check out usort : http://php.net/manual/en/function.usort.php
You'll have to write your own comparison function.

Find the most recent date from a nested array

I have a Multilevel Array (See array structure picture below) and I need to get the sub-nested array with the higher date value.
I was wondering if there is a straight forward way to sort sub-nested arrays by date value or get the highest date value?
Array Map
To do that, usort() function will be useful:
usort($rgData, function($rgX, $rgY)
{
$x = strtotime($rgX['date']);
$y = strtotime($rgY['date']);
return $x<$y?-1:$x!=$y;
});
//var_dump($rgData);
if you want to get highest value, then it will be ['date'] key of last element after doing the sort above.
Edit: if you're sure that format will be exactly same as on picture always, you can use direct string comparison via strcmp (that would be probably faster)
How about using usort():
$input = array(
array('date' => '2013-09-11 13:08:40 +0000'),
array('date' => '2013-09-11 13:09:17 +0000'));
usort($input, function(array $a, array $b) {
$aTimestamp = strtotime($a['date']);
$bTimestamp = strtotime($b['date']);
if($aTimestamp == $bTimestamp) return 0;
return $aTimestamp < $bTimestamp;
});
print_r($input); //$input[0] has the latest date value

Categories