i want to sort an array in php [duplicate] - php

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 3 years ago.
Array
(
[0] => Array
(
[count] => 9
[slug] => concediat-reangajat
)
[1] => Array
(
[count] => 7
[slug] => salarii-5togo
)
[2] => Array
(
[count] => 10
[slug] => piata-fortei-munca
)
[3] => Array
(
[count] => 3
[slug] => productivitate-angajati
)
[4] => Array
(
[count] => 1
[slug] => stocare-date
)
[5] => Array
(
[count] => 4
[slug] => infrastructura-leadership
)
[6] => Array
(
[count] => 2
[slug] => airbnb-uber
)
[7] => Array
(
[count] => 5
[slug] => salarii-productivitate
)
[8] => Array
(
[count] => 2
[slug] => ceo-resurse-umane
)
[9] => Array
(
[count] => 3
[slug] => hr-ceo
)
[10] => Array
(
[count] => 1
[slug] => burnout-tratament
)
[11] => Array
(
[count] => 1
[slug] => angajati-vanzarea-afacerii
)
[12] => Array
(
[count] => 1
[slug] => job-linkedin
)
[13] => Array
(
[count] => 1
[slug] => primul-faliment
)
[14] => Array
(
[count] => 3
[slug] => salariu-mic
)
[15] => Array
(
[count] => 1
[slug] => varsta-programatori
)
)
i want to sort this array based on decending order of count
this array contains arrays of data
count and a slug variable
i want to sort whole array based on descending order of count
how i can sort this.. anybody can help me
i tried usort,ksort etc
am new in programming
not getting a solution
please help me
i tried for a solution
but its didnt work
anybody can solve it?

usort with callback will work for you.
usort($array, function($a, $b) {
return $b['count'] - $a['count']; # $a['count'] - $b['count']; will sort asc
});
WORKING DEMO: https://3v4l.org/SUa2F
OR do simple with arsort($array);
WORKGING DEMO: https://3v4l.org/bnWuo

Reverse sort by count descending (and name ascending for like counts):
<?php
$items =
[
['count'=>2, 'name' => 'Janitor'],
['count'=>5, 'name' => 'Plumber'],
['count'=>1, 'name' => 'Scrubber'],
['count'=>3, 'name' => 'Winkle Picker'],
['count'=>3, 'name' => 'Window Cleaner']
];
usort($items, function($a, $b) {
$compare = $b['count'] <=> $a['count'];
if($compare == 0)
$compare = $a['name'] <=> $b['name'];
return $compare;
});
var_export($items);
Output:
array (
0 =>
array (
'count' => 5,
'name' => 'Plumber',
),
1 =>
array (
'count' => 3,
'name' => 'Window Cleaner',
),
2 =>
array (
'count' => 3,
'name' => 'Winkle Picker',
),
3 =>
array (
'count' => 2,
'name' => 'Janitor',
),
4 =>
array (
'count' => 1,
'name' => 'Scrubber',
),
)

Related

Sort array based on different columns

I created an array based on a mysql table
Array (
[0] => Array ( [id] => 1 [parent_ID] => 0 )
[1] => Array ( [id] => 2 [parent_ID] => 0 )
[2] => Array ( [id] => 3 [parent_ID] => 2 )
[3] => Array ( [id] => 4 [parent_ID] => 2 )
[4] => Array ( [id] => 5 [parent_ID] => 2 )
[5] => Array ( [id] => 6 [parent_ID] => 1 )
[6] => Array ( [id] => 7 [parent_ID] => 1 )
[7] => Array ( [id] => 8 [parent_ID] => 1 )
[8] => Array ( [id] => 9 [parent_ID] => 1 )
I want to create a new array, where the order of the parent_ID is based on the ID. If the parent_ID from an array is “1”, than it needs to be placed directly after the array that has ID “1”. The output of the new array needs to be like this:
Array (
[0] => Array ( [id] => 1 [parent_ID] => 0 )
[1] => Array ( [id] => 6 [parent_ID] => 1 )
[2] => Array ( [id] => 7 [parent_ID] => 1 )
[3] => Array ( [id] => 8 [parent_ID] => 1 )
[4] => Array ( [id] => 9 [parent_ID] => 1 )
[5] => Array ( [id] => 2 [parent_ID] => 0 )
[6] => Array ( [id] => 3 [parent_ID] => 2 )
[7] => Array ( [id] => 4 [parent_ID] => 2 )
[8] => Array ( [id] => 5 [parent_ID] => 2 )
I tried to order my array by using the usort function, but that will only order the parent_ID or the ID column. Is it possible with PHP to sort an array like the example?
As said in my comment to the question your proposed result is bogus...
But here is some simple algorithm constructing such output:
<?php
$input = [
['id' => 1, 'parent_ID' => 0],
['id' => 2, 'parent_ID' => 0],
['id' => 3, 'parent_ID' => 2],
['id' => 4, 'parent_ID' => 2],
['id' => 5, 'parent_ID' => 2],
['id' => 6, 'parent_ID' => 1],
['id' => 7, 'parent_ID' => 1],
['id' => 8, 'parent_ID' => 1],
['id' => 9, 'parent_ID' => 1]
];
$data = [];
$output = [];
array_walk ($input, function($entry) use (&$data) {
$data[$entry['parent_ID']][] = $entry;
});
array_walk ($data[0], function($entry) use ($data, &$output) {
$output[] = $entry;
foreach ($data[$entry['id']] as $child) {
$output[] = $child;
}
});
print_r($output);
The output of executing that obviously is:
Array
(
[0] => Array
(
[id] => 1
[parent_ID] => 0
)
[1] => Array
(
[id] => 6
[parent_ID] => 1
)
[2] => Array
(
[id] => 7
[parent_ID] => 1
)
[3] => Array
(
[id] => 8
[parent_ID] => 1
)
[4] => Array
(
[id] => 9
[parent_ID] => 1
)
[5] => Array
(
[id] => 2
[parent_ID] => 0
)
[6] => Array
(
[id] => 3
[parent_ID] => 2
)
[7] => Array
(
[id] => 4
[parent_ID] => 2
)
[8] => Array
(
[id] => 5
[parent_ID] => 2
)
)
However I would like to make some comments to your situation:
you really should not store a value of 0 for the first elements. They do not have a parent, if I get your situation right, so that value should actually be null, not 0.
you should try to order your data right in the SQL query
you should rethink the overall approach since apparently you have huge issues sorting your data with the given data model. That typically is a sign of a modelling approach that should be reworked.

Sort multi-dimensional array by considering 2 different properties

I have an array for example
Array
(
[0] => Array
(
[id] => 6
[name] => ah
[order] => 4
)
[1] => Array
(
[id] => 5
[name] => hz
[order] =>
)
[2] => Array
(
[id] => 7
[name] => ch
[order] =>
)
[3] => Array
(
[id] => 5
[name] =>
[order] =>
)
[4] => Array
(
[id] => 4
[name] => zh
[order] => 1
)
)
It needs to be sorted first by "order", if order isn't available, it is sorted in alphabetical order with the "name" (but those arrays goes after all the arrays that have the sort order), and if no "order" and no "name", it goes at the end of the array.
So the above array would need to become:
Array
(
[0] => Array
(
[id] => 4
[name] => zh
[order] => 1
)
[1] => Array
(
[id] => 6
[name] => ah
[order] => 4
)
[2] => Array
(
[id] => 7
[name] => ch
[order] =>
)
[3] => Array
(
[id] => 5
[name] => hz
[order] =>
)
[4] => Array
(
[id] => 5
[name] =>
[order] =>
)
)
I've tried some for looping but nothing close to a solution.
Have you looked at array_multisort?
foreach ($data as $key => $row) {
$name[$key] = $row['name'];
$order[$key] = $row['order'];
}
array_multisort($name, SORT_DESC, $order, SORT_ASC, $data);
PHP array multisort
array_multisort() might not provide enough control to achieve the sorting you require.
As an alternative, you could use uasort() and provide a custom comparison function.
For example:
function compare($a, $b) {
if (empty($a['order']) && !empty($b['order'])) {
return 1;
}
if (!empty($a['order']) && empty($b['order'])) {
return -1;
}
if ($a['order'] == $b['order']) {
return strnatcmp($a['name'], $b['name']);
}
return ($a['order'] < $b['order']) ? -1 : 1;
}
uasort($arr, 'compare');

How can I sort multidimensional array through key

Array
(
[12] => Array
(
[id] => 12
[name] => Car
[children] => Array
(
[0] => Array
(
[id] => 14
[name] => Volvo
)
[1] => Array
(
[id] => 15
[name] => Mercedes-Benz
)
)
)
[13] => Array
(
[id] => 13
[name] => Manga
[children] => Array
(
[0] => Array
(
[id] => 16
[name] => Naruto
)
[1] => Array
(
[id] => 17
[name] => Hunter X Hunter
)
)
)
[18] => Array
(
[id] => 18
[name] => aa
[children] => Array
(
)
)
)
Guys I want to sort the values of this array, i want to sort it by key and the key is 'name'. This should sort the first level and the second level thru key 'name'.
This array i put in print_r() so it looks like this. The array is not fix so i can add in the future.
So after sorting the final value of the array is...
Array
(
[18] => Array
(
[id] => 18
[name] => aa
[children] => Array
(
)
)
[12] => Array
(
[id] => 12
[name] => Car
[children] => Array
(
[0] => Array
(
[id] => 15
[name] => Mercedes-Benz
)
[1] => Array
(
[id] => 14
[name] => Volvo
)
)
)
[13] => Array
(
[id] => 13
[name] => Manga
[children] => Array
(
[0] => Array
(
[id] => 17
[name] => Hunter X Hunter
)
[1] => Array
(
[id] => 16
[name] => Naruto
)
)
)
)
And this is the array in code.
$categories = array(
12 =>
array('id' =>12,
'name' => 'Car',
'children' =>
array(
array('id' => 14,
'name' => 'volvo'
)
),
array(
array('id' => 15,
'name' => 'Mercedez-Benz'
)
)
),
13 =>
array('id' =>13,
'name' => 'Manga',
'children' =>
array(
array('id' => 16,
'name' => 'Naruto'
)
),
array(
array('id' => 17,
'name' => 'Hunter X Hunter'
)
)
),
18=>
array('id' => 18,
'name'=> 'aa',
'children' => array())
);
echo "<pre>";
print_r($categories);
the 'name' is not your real 'Key', just saying, because 'key' in Php normally means the name of your array, like '18' and '12' in your array and so on, like this:
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
in this example, the result will be:
a = orange
b = banana
c = apple
d = lemon
anyway to answer your question on how to sort it on 'name', use 'usort':
function cmp($a, $b) {
return $a['name'] - $b['name'];
}
usort($arr,"cmp");
check out the following link for further information:
How do I sort a PHP array by an element nested inside?
if using php 5.3+ you can use closures in your code and sort like this
usort($categories,function($a,$b){
return $a['name'] - $b['name']
}
So,
I'm going to try and explain it better to you
your array is big, yes, but you want to sort only on the key value '[name]'.
In my test I used the array you provided:
$categories = array(
12 =>
array('id' =>12,
'name' => 'Car',
'children' =>
array(
array('id' => 14,
'name' => 'volvo'
)
),
array(
array('id' => 15,
'name' => 'Mercedez-Benz'
)
)
),
13 =>
array('id' =>13,
'name' => 'Manga',
'children' =>
array(
array('id' => 16,
'name' => 'Naruto'
)
),
array(
array('id' => 17,
'name' => 'Hunter X Hunter'
)
)
),
18=>
array('id' => 18,
'name'=> 'aa',
'children' => array())
);
if the array is declared, you can add the usort like this:
usort($categories,"sortByName");
the first element in the above ($categories), is your array, the second element will provide the name of a function, in this case 'sortByName'.
after that, you just add a function into your code (it doesn't really matter where you put it, even if it's at the bottom of the page):
function sortByName($categories, $b) {
return strcasecmp($categories["name"], $b["name"]);
}
Basically what this function does, is compairing your array with ...your array :) so it can sort it alfabetically by name- like you want it.
sthe 'strcasecmp' is to compare your strings against eachother to sort it. not that this is case non sensitive (strcmp will be case sensitive too). I assume you don't want it to check on uppercase and so on too, otherwise the result won't be what you wanted.
when you added that code, you can just print your array again:
echo "<pre>";
print_r($categories);
your result will be:
Array
(
[0] => Array
(
[id] => 18
[name] => aa
[children] => Array
(
)
)
[1] => Array
(
[id] => 12
[name] => Car
[children] => Array
(
[0] => Array
(
[id] => 14
[name] => volvo
)
)
[0] => Array
(
[0] => Array
(
[id] => 15
[name] => Mercedez-Benz
)
)
)
[2] => Array
(
[id] => 13
[name] => Manga
[children] => Array
(
[0] => Array
(
[id] => 16
[name] => Naruto
)
)
[0] => Array
(
[0] => Array
(
[id] => 17
[name] => Hunter X Hunter
)
)
)
I hope this is what you wanted. :-)

Get top 5 values from multidimensional array in PHP [duplicate]

This question already has answers here:
How to sort an array of arrays in php?
(3 answers)
php - usort or array_multisort?
(3 answers)
Get the first N elements of an array?
(5 answers)
PHP: Any function that return first/last N elements of an array
(2 answers)
Closed 2 years ago.
I have the following array:
Array (
[0] => Array (
[count] => 9
[user_id] => 2
)
[1] => Array (
[count] => 25
[user_id] => 1
)
[2] => Array (
[count] => 20
[user_id] => 3 )
[3] => Array (
[count] => 6
[user_id] => 56 )
[4] => Array (
[count] => 2
[user_id] => 37 )
[5] => Array (
[count] => 1
[user_id] => 0
))
This is just a sample. The actual array will contain many more sub arrays.
I need to be able to obtain the top five values from "count" and store them with their associated "user_id".
The final result needs to look something like this:
Array (
[0] => Array (
[count] => 25
[user_id] => 1
)
[1] => Array (
[count] => 20
[user_id] => 3
)
[2] => Array (
[count] => 9
[user_id] => 2
)
[3] => Array (
[count] => 6
[user_id] => 56
)
[4] => Array (
[count] => 2
[user_id] => 37
)
[5] => Array (
[count] => 1
[user_id] => 0
) )
If this can be done by simply re ordering the array, that is fine.
Thanks!
You're looking for usort and array_slice.
Example:
<?php
$array = array(
array(
'count' => 9,
'user_id' => 2
),
array(
'count' => 25,
'user_id' => 1
),
array(
'count' => 20,
'user_id' => 3
),
array(
'count' => 6,
'user_id' => 56
),
array(
'count' => 2,
'user_id' => 37
),
array(
'count' => 1,
'user_id' => 0
)
);
function usort_callback($a, $b)
{
if ( $a['count'] == $b['count'] )
return 0;
return ( $a['count'] > $b['count'] ) ? -1 : 1;
}
usort($array, 'usort_callback');
$top5 = array_slice($array, 0, 5);
print_r($top5);
Outputs:
Array
(
[0] => Array
(
[count] => 25
[user_id] => 1
)
[1] => Array
(
[count] => 20
[user_id] => 3
)
[2] => Array
(
[count] => 9
[user_id] => 2
)
[3] => Array
(
[count] => 6
[user_id] => 56
)
[4] => Array
(
[count] => 2
[user_id] => 37
)
)
usort($array, function ($a, $b) { return $b['count'] - $a['count']; });
$top5 = array_slice($array, 0, 5);

Sorting arrays numerically [duplicate]

This question already has answers here:
Sort an array of associative arrays by column value
(23 answers)
Closed 4 months ago.
I have a PHP array that I need to sort. I have included the example array below. I need to put the top 10 number of URLS plus their perspective counts in a different array. I know I could run into problem if there aren't 10 top matches ... if that happens then a random matching would be fine.
Any suggestions?
I have tried sort(myarray) but that just sorts the first object in the array I need it to sort the second.
Any ideas?
Array
(
[0] => Array
(
[name] => http://bit.ly/2oUTzf
[count] => 1
)
[1] => Array
(
[name] => http://tiny.cc/wyNbi
[count] => 1
)
[2] => Array
(
[name] => http://ow.ly/Almo
[count] => 1
)
[3] => Array
(
[name] => http://bit.ly/7bQ8sY
[count] => 1
)
[4] => Array
(
[name] => http://kissa.be/w4V-
[count] => 5
)
[5] => Array
(
[name] => http://ow.ly/xzwI
[count] => 1
)
[6] => Array
(
[name] => http://twa.lk/L6FZX
[count] => 1
)
[7] => Array
(
[name] => http://tinyurl.com/Alyssa10
[count] => 1
)
[8] => Array
(
[name] => http://www.hiderefer.com/0cz7kNgA.htm
[count] => 1
)
[9] => Array
(
[name] => http://tinyurl.com/Joanie515
[count] => 1
)
[10] => Array
(
[name] => http://ow.ly/uJvB
[count] => 1
)
[11] => Array
(
[name] => http://tinyurl.com/
[count] => 1
)
[12] => Array
(
[name] => http://www.hiderefer.com/wJBUhh3G.htm
[count] => 1
)
[13] => Array
(
[name] => http://short.to/xcxc
[count] => 1
)
[14] => Array
(
[name] => http://bit.ly/t79FA
[count] => 2
)
[15] => Array
(
[name] => http://tinyurl.com/yzy33yl
[count] => 1
)
[16] => Array
(
[name] => http://p.gs/zksz6
[count] => 1
)
[17] => Array
(
[name] => http://bit.ly/7E1cc8
[count] => 1
)
[18] => Array
(
[name] => http://bit.ly/6hbugu
[count] => 1
)
[19] => Array
(
[name] => http://tii.libsyn.com/index.php
[count] => 6
)
[20] => Array
(
[name] => http://tinyurl.com/nlzzwq
[count] => 1
)
[21] => Array
(
[name] => http://bit.ly/7gAdXi
[count] => 1
)
[22] => Array
(
[name] => http://localtweeps.com
[count] => 1
)
[23] => Array
(
[name] => http://localtweeps.com.
[count] => 3
)
[24] => Array
(
[name] => http://scribd.com/doc/22365778
[count] => 1
)
[25] => Array
(
[name] => http://quick-weight-loss-secrets.com/
[count] => 1
)
[26] => Array
(
[name] => http://tinyurl.com/ykd5qm5
[count] => 1
)
[27] => Array
(
[name] => http://bit.ly/5DQ6SO
[count] => 1
)
[28] => Array
(
[name] => http://bit.ly/4z6Kww
[count] => 1
)
[29] => Array
(
[name] => http://bit.ly/40sm9N
[count] => 1
)
[30] => Array
(
[name] => http://bit.ly/8mh7DO
[count] => 5
)
[31] => Array
(
[name] => http://tinyurl.com/krt5yf
[count] => 1
)
[32] => Array
(
[name] => http://bit.ly/7GsthV
[count] => 1
)
[33] => Array
(
[name] => http://bit.ly/1QJzvM
[count] => 1
)
[34] => Array
(
[name] => http://yfrog.com/1durkj
[count] => 1
)
[35] => Array
(
[name] => http://budurl.com/dxwc
[count] => 9
)
[36] => Array
(
[name] => http://digg.com/d1qiCr
[count] => 1
)
[37] => Array
(
[name] => http://bit.ly/eVSIo
[count] => 1
)
[38] => Array
(
[name] => http://yfrog.com/37badgj
[count] => 2
)
[39] => Array
(
[name] => http://tinyurl.com/qh8sos
[count] => 1
)
[40] => Array
(
[name] => http://tinyurl.com/mz7l8d
[count] => 3
)
[41] => Array
(
[name] => http://tinyurl.com/nratac
[count] => 1
)
[42] => Array
(
[name] => http://tinyurl.com/yk587jx
[count] => 1
)
[43] => Array
(
[name] => http://www.bethel.edu/alumni/homecoming/09/events/
[count] => 1
)
[44] => Array
(
[name] => http://www.waytofit.net
[count] => 1
)
[45] => Array
(
[name] => http://twitpic.com/rdcy8
[count] => 1
)
[46] => Array
(
[name] => http://retwt.me/1C1Vd
[count] => 14
)
[47] => Array
(
[name] => http://www.starbucks.com/card
[count] => 1
)
[48] => Array
(
[name] => http://tinyurl.com/yhkbfqe
[count] => 13
)
[49] => Array
(
[name] => http://bit.ly/playspy
[count] => 1
)
[50] => Array
(
[name] => http://bit.ly/57rHLO
[count] => 12
)
You need to write a custom sorting function - like this:
function MyCustomSort($a, $b)
{
if ($a->count == $b->count) {
return 0;
}
return ($a->count < $b->count) ? -1 : 1;
}
Then you pass that function into a sort - like this:
usort($myArray, "MyCustomSort");
You could also write a function to help you sort by website - like this:
function MyCustomSort($a, $b)
{
if ($a->name == $b->name) {
return 0;
}
return ($a->name < $b->name) ? -1 : 1;
}
You may use decorate-sort-undecorate pattern.
<?php
$arr = Array
(
[0] => Array
(
[name] => http://bit.ly/2oUTzf
[count] => 1
)
[1] => Array
(
[name] => http://tiny.cc/wyNbi
[count] => 1
)
[2] => Array
(
[name] => http://ow.ly/Almo
[count] => 1
)
[3] => Array
(
[name] => http://bit.ly/7bQ8sY
[count] => 1
)
...
);
// actual sorting below
$arr= array_map(create_function('$a', 'return array($a["count"], $a);'), $arr); // transform into array of arrays consisted of sort key and item
sort($arr); // sort array of arrays
$arr = array_map('end', $arr); // take only last element from each array
print_r($arr);
How does it work?
Instead of sorting array of your items you sort array of arrays whose last element is item and first is the key by which you want to sort. After sorting you keep only the item.
You can use just sort for sorting array of arrays because PHP compares two same length arrays by comparing its elements one by one.
Sorting by multiple fields
You may use more then one sort key, for example sort by count and if counts are identical take url into account. You can do this by decorating with multiple keys with order of importance like so:
$arr = array_map(create_function('$a', 'return array($a["count"], $a["name"], $a);'), $arr);
Why it's fast
This way might be faster that using usort because it calls your custom code only n-times for sorting array of length n. Comparisons during sort are done using built in comparator so should be fast. In usort method custom comparator is called multiple times (more than n times) during sort and it may slow down things.
function sortByCount($a, $b)
{
if ($a['count'] == $b['count']) {
return 0;
}
return ($a['count'] < $b['count']) ? -1 : 1;
}
usort($myarray, "sortByCount");

Categories