Multi-Dimensional array sort first and second [duplicate] - php

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 8 years ago.
I'm using a function called subval_sort to sort a multi-dimensional array.
function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}
$songs = array(
'1' => array('artist'=>'Bing Crosby', 'songname'=>'White Christmas'),
'2' => array('artist'=>'Elvis Presley', 'songname'=>'White Christmas'),
'3' => array('artist'=>'Abba', 'songname' =>'Waterloo')
);
$songs = subval_sort($songs,'songname');
print_r($songs);
Works fine. Now I want to sort by songname as first and artist as second. So: if two (or more) songname-values are the same I want to sort by artist. Like in SQL: ORDER BY songname, artist.
Do you have any ideas how to solve it?

You can use usort where you can define the custom comparison function
function cmp($a, $b)
{
if(strcmp($a['songname'], $b['songname'])) {
return strcmp($a['songname'], $b['songname']);
}
return strcmp($a["artist"], $b["artist"]);
}
implementation:
usort($songs, "cmp");

Related

php sort associative array by specific key [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 6 years ago.
Problem: I have an associative multi-dimensional array with each key having an array inside. It looks like this:
array(3){
[1]=>
"id"=>1
"name"=>"Test #1"
"listorder"=>1
[6]=>
"id"=>6
"name"=>"Test #1"
"listorder"=>3
[2]=>
"id"=>2
"name"=>"Test #2"
"listorder"=>2
}
I need to sort this array by each array's listorder value without changing any of the key numbers. How can this be done?
I am currently trying this code which I got from a separate Stack overflow question.
function sort_array(){
foreach($array as $key => $row){
$listorder[$row["id"]] = $row["listorder"];
}
array_multisort($listorder, SORT_ASC, $array);
return $array;
}
But this specific code rewrites all of the key numbers. Is there another way to sort without changing anything?
The best possible way is to use uasort() function.
Try this:
$array = array(
1 => array(
"id"=>1,
"name"=>"Test #1",
"listorder"=>1
),
6 => array(
"id"=>6,
"name"=>"Test #1",
"listorder"=>3
),
2 => array(
"id"=>2,
"name"=>"Test #2",
"listorder"=>2
)
);
function sort_count($a, $b) {
if ($a['listorder'] === $b['listorder']) {
return 0;
} else {
return ($a['listorder'] > $b['listorder'] ? 1:-1);
}
}
$sorted_array = uasort($array, 'sort_count');
echo "<pre>";
print_r($array);
echo "</pre>";
you can try to sort by creating a new array, with array_keys:
function sort_array($array)
{
$keys = array_keys($array);
$out = array();
$listorder = array();
foreach($array as $key => $row)
{
$listorder[$row["id"]] = $row["listorder"];
}
array_multisort($listorder, SORT_ASC, $keys);
foreach($keys as $k)
{
$out[$k] = $array[$k];
}
return $out;
}
It should only sort the 'keys' array (which contain keys of array).
And then you rebuild the sorted $array in $out
You can try this short and sweet piece of code:
uasort($data,function($a,$b){
return strcmp($a["listorder"],$b["listorder"]);
});
print_r($data);
Working Demo is Here

How to sort associative arrays by value of a given key and maintain key in php? [duplicate]

This question already has answers here:
Sort an array of associative arrays by column value
(23 answers)
Closed 7 years ago.
Given this array
$inventory = array(
"sdfsdfsdsx65fsdf1"=>array("type"=>"fruit", "price"=>3.50),
"sdfsdfsdsx65fsdf2"=>array("type"=>"milk", "price"=>2.90),
"sdfsdfsdsx65fsdf3"=>array("type"=>"pork", "price"=>5.43)
);
I want output like below
$inventory = array(
"sdfsdfsdsx65fsdf3"=>array("type"=>"pork", "price"=>5.43),
"sdfsdfsdsx65fsdf1"=>array("type"=>"fruit", "price"=>3.50),
"sdfsdfsdsx65fsdf2"=>array("type"=>"milk", "price"=>2.90)
);
$inventory = array(
array("sdfsdfsdsx65fsdf1"=>array("type"=>"fruit", "price"=>3.50)),
array("sdfsdfsdsx65fsdf2"=>array("type"=>"milk", "price"=>2.90)),
array("sdfsdfsdsx65fsdf3"=>array("type"=>"pork", "price"=>5.43))
);
usort($inventory, function($a, $b) {
foreach ($a as $a);
foreach ($b as $b);
if ($a['price'] == $b['price']) return 0;
return ($a['price'] < $b['price']) ? 1 : -1;
});
print_r($inventory);

PHP Multisort array on more than 2 criteria [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 7 years ago.
I wrote a php script that will execute a full (dutch) soccer competition, based on parameters as Strength and moral.
After all rounds have been 'played', I use usort to define the end results.
These results are based on the 'Points' field. However, when two teams share the same number of points, further ranking has to be achieved by comparing the goal difference.
I tried to accomplish this sorting using first sorting om 'Points' and after that sorting om 'GoalDifference (GD)'. Unfortunately in the latter case goaldifference is sorted correctly but not the Points...
This is what the teams array looks like now:
$teams = array
(
array(
'Id' => 1,
'Teamname' => 'Team 1,
'Strength' => 22,
'Moral' => 15,
'Points' => 0,
'Pro' => 0,
'Contra'=> 0,
'GD' => 0
)
}
Below the usort functions
usort($teams, function($a, $b) {
return $a['Points'] < $b['Points'];
});
usort($teams, function($a, $b) {
return $a['GD'] < $b['GD'];
});
So my question is, what is the best way to first sort on points and after that on goaldifference?
Kind regards,
Kees
You can build an more complex sort function where you check the columns in priority.
usort($teams, function($a, $b) {
if ($a["Points"] < $b["Points"]) return -1;
if ($a["Points"] > $b["Points"]) return 1;
if ($a['GD'] < $b['GD']) return -1;
if ($a['GD'] > $b['GD']) return 1;
return 0;
});
Include both comparisons at the same time. So if the points are the same, use goal difference
usort($teams, function($a, $b) {
return ($a['Points'] === $b['Points']
? $a['GD'] < $b['GD']
: $a['Points'] < $b['Points']);
});
You can use array_multisort() function.
$points = array();
$gd = array();
foreach ($teams as $key => $row) {
$points[$key] = $row['Points'];
$gd[$key] = $row['GD'];
}
array_multisort($points, SORT_DESC, $gd, SORT_DESC, $teams);

Sort multidimensional array in PHP [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 8 years ago.
I have a multidimensional array, fetched from an SQL query. It looks like this:
$CIKK[$j]["vonalkod"]
$CIKK[$j]["kiadva"]
$CIKK[$j]["nev"]
$CIKK[$j]["hatarido"]
Can I sort $CIKK based on the value of its ["vonalkod"]?
you use this function
function sort_multi($array, $column, $method) {
foreach ($array as $key => $row) {
$narray[$key] = $row[$column];
}
array_multisort($narray, $method, $array);
return $array;
}
$myarray = sort_multi($CIKK , 'vonalkod' , SORT_DESC)
i'm using array_multisort in http://php.net/manual/en/function.array-multisort.php
the $method will take SORT_DESC or SORT_ASC

How can you sort each element inside of an array alphabetically [duplicate]

This question already has answers here:
PHP: How to sort the characters in a string?
(5 answers)
Closed 8 years ago.
For example we have the following words: hey, hello, wrong
$unsorted = array("eyh", "lhleo", "nrwgo");
I know that I could use asort to sort the array alphabetically, but I don't want that.
I wish to take the elements of the array and sort those, so that it would become something like this:
$sorted = array("ehy", "ehllo", "gnorw"); // each word in the array sorted
hey sorted = ehy
hello sorted = ehllo
wrong sorted = gnorw
As far as I know, the function sort will only work for arrays, so if you attempt to sort a word using sort, it will produce an error. If I had to assume, I will probably need to use a foreach along with strlen and a for statement or something similar, but I am not sure.
Thanks in advance!
function sort_each($arr) {
foreach ($arr as &$string) {
$stringParts = str_split($string);
sort($stringParts);
$string = implode('', $stringParts);
}
return $arr;
}
$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = sort_each($unsorted);
print_r($sorted); // returns Array ( [0] => ehy [1] => ehllo [2] => gnorw )
$myArray = array("eyh", "lhleo", "nrwgo");
array_walk(
$myArray,
function (&$value) {
$value = str_split($value);
sort($value);
$value = implode($value);
}
);
print_r($myArray);
Try this
$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = array();
foreach ($unsorted as $value) {
$stringParts = str_split($value);
sort($stringParts);
$sortedString = implode('', $stringParts);
array_push($sorted, $sortedString);
}
print_r($sorted);

Categories