Sort sub elements of array - php

I have an array like this one:
Array
(
[0] => Array
(
[id] => 1
[name] => Mickey
)
[1] => Array
(
[id] => 2
[name] => Donald
)
[2] => Array
(
[id] => 3
[name] => Goofy
)
)
Is there a way to sort in alphabetical order the 'name' field?

Yes, there is. Using a callback method for usort();
function my_sorter($a, $b) {
return strcmp($a['name'], $b['name']);
}
usort($list, 'my_sorter');

You could use usort() http://php.net/manual/en/function.usort.php

usort works fine. The function passed to usort should be a comparison function, which returns a value less than one if ab, and 0 if a==b. Because of how your arrays are formatted, your comparison function should compare a['name'] and b['name']. So:
function cmp($a, $b)
{
return strcmp($a['name'],$b['name']);
}
$a = array(array("id" => 2, "name" => "Donald"),array("id" => 3, "name" => "Goofy"),array("id" => 4, "name" => "Mickey"));
usort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: ".$value['name']."\n";
}

Related

how can I get sorting multidimnsion array by value?

How can I sorting multidimension array by value?
Example my output array like this :
[0] => Array
(
[0] => 2
[1] => 5
[2] => 8
[3] => 1
)
[1] => Array
(
[0] => 7
[1] => 4
[2] => 1
)
Can I get sorted array like this?
[0] => Array
(
[3] => 1
[0] => 2
[1] => 5
[2] => 8
)
[1] => Array
(
[2] => 1
[1] => 4
[0] => 7
)
Thanks..
simple way with asort
array_map(function($v){asort($v); return $v;}, $array);
Or you can use uasort()
You can use uasort and array_map to sort the elements. for php7+
array_map(function($v){uasort($v, function($a, $b){return $a <=> $b;}); return $v;}, $array);
for version<7 use this compare funciton of uasort
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
You can use array_walk together with asort:
array_walk($array, 'asort');
Here is working demo.
You can use arsort to sort array by values. make a loop and call asort($arr) for each sub array you have

How can I sort the sub arrays from a multidimensional array by keys?

I have this array for example:
$exampleArray = array (
array( 'Name' => 'Opony', 'Kod' =>'OPO', 'Price' => 100 ),
array( 'Kod' =>'OLE', 'Name' => 'Olej', 'Price' => 20 ),
array( 'Kod' =>'ABC', 'Price' => 20, 'Name' => 'abcdefg' )
)
Keys in sub array are in random order. I want to sort the sub arrays by key:
Array
(
[0] => Array
(
[Kod] => OPO
[Name] => Opony
[Price] => 100
)
[1] => Array
(
[Kod] => OLE
[Name] => Olej
[Price] => 20
)
I try this:
function compr($x,$y){
if($x == $y)
return 0;
elseif($x>$y)
return 1;
elseif($x<$y)
return-1;
}
uksort($exampleArray, 'compr');
print_r($exampleArray);
But this code doesn't give me my expected result, what is wrong, how can I solve it?
This should work for you:
Just loop through all of your inner Arrays by reference and then just use uksort() with strcasecmp() to sort your inner Arrays by the keys.
foreach($exampleArray as &$v) {
uksort($v, function($a, $b){
return strcasecmp($a, $b);
});
}
unset($v); //So if you use $v later it doesn't change the last element of the array by reference
output:
Array
(
[0] => Array
(
[Kod] => OPO
[Name] => Opony
[Price] => 100
)
//...
[2] => Array
(
[Kod] => ABC
[Name] => abcdefg
[Price] => 20
)
)
There is ABSOLUTELY no reason to call a user-defined sorting algorithm (uksort()) here.
Just call ksort() on each row.
Code: (Demo)
foreach ($array as &$row) {
ksort($row);
}
var_export($array);
Or (Demo)
array_walk($array, fn(&$row) => ksort($row));
var_export($array);
Or (Demo)
function keySortRow(array $row): array {
ksort($row);
return $row;
}
var_export(
array_map('keySortRow', $array)
);

How do I sort a multidimensional array with stdClass Objects by values of a key? [duplicate]

This question already has answers here:
How do I sort a multidimensional array by one of the fields of the inner array in PHP? [duplicate]
(8 answers)
Closed last year.
Yes, I have searched and tried many techniques, but nothing seems to work. Here is my array:
Array
(
[0] => stdClass Object
(
[id] => 119
[name] => Business3
[start_date] => 1338789600
[end_date] => 1354604400
)
[1] => stdClass Object
(
[id] => 153
[name] => Business1
[start_date] => 1338962400
[end_date] => 1370498400
)
[2] => stdClass Object
(
[id] => 135
[name] => Business2
[start_date] => 1339653600
[end_date] => 1356937200
)
)
I basically want to sort this by the name key, but every function I've tried on Stackoverflow doesn't seem to work, as in, I get a blank page with no error.
I tried this:
function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
$sort_col = array();
foreach ($arr as $key=> $row) {
$sort_col[$key] = $row[$col];
}
array_multisort($sort_col, $dir, $arr);
}
array_sort_by_column(json_decode(json_encode($businesses), true), 'name');
But that didn't work.
Any ideas?
You're almost right, but $row[$col] tries to access the objects like an array. You want something like $row->{$col} instead. Here's a simpler, working example:
$db = array(
0 => (object) array('name' => 'Business3'),
1 => (object) array('name' => 'Business2'),
2 => (object) array('name' => 'Business1')
);
$col = 'name';
$sort = array();
foreach ($db as $i => $obj) {
$sort[$i] = $obj->{$col};
}
$sorted_db = array_multisort($sort, SORT_ASC, $db);
print_r($db);
Outputs:
Array
(
[0] => stdClass Object
(
[name] => Business1
)
[1] => stdClass Object
(
[name] => Business2
)
[2] => stdClass Object
(
[name] => Business3
)
)
usort($array, function($a, $b) {
return strcmp($a->name, $b->name);
});
You should use usort...
So you define a function that compares two objects (by the name field) and then run usort on the array, passing in the function as the second argument.
Something like this:
function cmp($a, $b)
{
if ($a["name"] == $b["name"]) {
return 0;
}
return ($a["name"] < $b["name"]) ? -1 : 1;
}
usort ($my_array, "cmp");
var_dump($my_array);
Hope that helps!
Ben

PHP array sort using inner val

Array
(
[1] => Array
(
[id] => 1
[sort] => 1
)
[3] => Array
(
[id] => 3
[sort] => 3
)
[2] => Array
(
[id] => 2
[sort] => 2
)
)
How do i sort it so its re-ordered using the inner 'sort' key ? ie the above would look like this:
Array
(
[1] => Array
(
[id] => 1
[sort] => 1
)
[2] => Array
(
[id] => 2
[sort] => 2
)
[3] => Array
(
[id] => 3
[sort] => 3
)
)
You can use usort with this comparison function:
function cmpBySort($a, $b) {
return $a['sort'] - $b['sort'];
}
usort($arr, 'cmpBySort');
Or you use array_multisort with an additional array of key values for the sort order:
$keys = array_map(function($val) { return $val['sort']; }, $arr);
array_multisort($keys, $arr);
Here array_map with the anonymous function is used to build an array of the sort values that is used to sort the array values itself. The advantage of this is that there is np comparison function that needs to be called for each pair of values.
Something like this:
usort($array, function (array $a, array $b) { return $a["sort"] - $b["sort"]; });
Something like this:
uasort($array, 'compfunc');
function compfunc($a, $b)
{
return $a['sort'] - $b['sort'];
}

sort an array base on key

i have an array like this:
Array
(
[0] => Array
(
[title] => some title
[time] => 1279231500
)
[1] => Array
(
[title] => some title 2
[time] => 1279231440
)
[2] => Array
(
[title] => some title 3
[time] => 1279229880
)
)
how i can sort it based on time?
You can sort it this way (since it is an associative array):
function cmp($a, $b)
{
return strcmp($a['time'], $b['time']);
}
usort($your_array, "cmp");
print_r($your_array);
As Gumbo mentioned, you should not use strcmp for integer values.
Use this function
function cmp($a, $b) {
if ($a['time'] == $b['time'])
return 0;
return ($a['time'] < $b['time']) ? -1 : 1;
}

Categories