Sorting arrays numerically [duplicate] - php

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");

Related

Sort Multidimensional Array using PHP

My PHP array ($array) is as follows:
Array
(
[channels] => Array
(
[0] => Array
(
[position] => 5
[id] => 11
[name] => AFK
)
[1] => Array
(
[position] => 1
[id] => 22
[name] => ARK
)
[2] => Array
(
[position] => 2
[id] => 33
[name] => ESO
)
[3] => Array
(
[position] => 4
[id] => 44
[name] => semi-afk
)
[4] => Array
(
[position] => 0
[id] => 55
[name] => SPACE
)
[5] => Array
(
[position] => 3
[id] => 66
[name] => Tanks & Ships
)
)
[instant_invite] =>
[id] => 123
[members] => Array
(
[0] => Array
(
[username] => Chartographer
[status] => online
[nick] => Chaz Rambone
[avatar_url] => https://cdn.discordapp.com/embed/avatars/0.png
[avatar] =>
[discriminator] => 3270
[id] => 124
)
[1] => Array
(
[username] => Chukers
[status] => online
[mute] =>
[suppress] =>
[deaf] =>
[channel_id] => 789
[game] => Array
(
[name] => The Elder Scrolls Online
)
[avatar_url] => https://cdn.discordapp.com/embed/avatars/1.png
[avatar] =>
[self_deaf] =>
[discriminator] => 9851
[self_mute] =>
[id] => 456
)
)
[name] => TEST
)
I want to sort by "position" starting at 0 and ASC.
I tried some of the examples found here but not getting it yet. Usort and a few others are not working for me. Sure it's syntax but not sure
if ($array->channels) {
usort($array->channels, function($a, $b) {
return $a->position > $b->position ? 1 : -1;
});
As was mentioned in the comments, you're trying to use object notation, but you're referencing an array. The documentation has very helpful examples.
usort($array['channels'], function($a, $b) {
return $a['position'] > $b['position'] ? 1 : -1;
});
See this fiddle example.

Iterating recursively through an array

Update: I have a solution - please see below for details.
I have an array where the keys are levels (in a navigation tree for example) - something like
Array
(
[0] => Array
(
[100] => Array
(
[name] => foo100
[slug] => foo100
[id] => 100
[parent] => 0
[level] => 0
)
[101] => Array
(
[name] => foo101
[slug] => foo101
[id] => 101
[parent] => 0
[level] => 0
)
)
[1] => Array
(
[200] => Array
(
[name] => foo200
[slug] => foo200
[id] => 200
[parent] => 100
[level] => 1
)
[201] => Array
(
[name] => foo201
[slug] => foo201
[id] => 201
[parent] => 101
[level] => 1
)
)
[2] => Array
(
[300] => Array
(
[name] => foo300
[slug] => foo300
[id] => 300
[parent] => 200
[level] => 2
)
[301] => Array
(
[name] => foo301
[slug] => foo301
[id] => 301
[parent] => 201
[level] => 2
)
)
[3] => Array
(
[400] => Array
(
[name] => foo400
[slug] => foo400
[id] => 400
[parent] => 300
[level] => 3
)
)
[4] => Array
(
[500] => Array
(
[name] => foo500
[slug] => foo500
[id] => 500
[parent] => 400
[level] => 4
)
)
)
I need to create an array from this which iterates from the top most level and creates an array with the key being the slug of that level - to produce the following:
Array
(
[foo500] => Array
(
[4] => Array
(
[name] => foo500
)
[3] => Array
(
[name] => foo400
)
[2] => Array
(
[name] => foo300
)
[1] => Array
(
[name] => foo200
)
[0] => Array
(
[name] => foo100
)
)
[foo400] => Array
(
[3] => Array
(
[name] => foo400
)
[2] => Array
(
[name] => foo300
)
[1] => Array
(
[name] => foo200
)
[0] => Array
(
[name] => foo100
)
)
[foo300] => Array
(
[2] => Array
(
[name] => foo300
)
[1] => Array
(
[name] => foo200
)
[0] => Array
(
[name] => foo100
)
)
[foo301] => Array
(
[2] => Array
(
[name] => foo301
)
[1] => Array
(
[name] => foo201
)
[0] => Array
(
[name] => foo101
)
)
[foo200] => Array
(
[1] => Array
(
[name] => foo200
)
[0] => Array
(
[name] => foo100
)
)
[foo201] => Array
(
[1] => Array
(
[name] => foo201
)
[0] => Array
(
[name] => foo101
)
)
[foo100] => Array
(
[0] => Array
(
[name] => foo100
)
)
[foo101] => Array
(
[0] => Array
(
[name] => foo101
)
)
)
I hope this explains the issue - struggling to get this right! Any help much appreciated!
Update - solution.
For this I removed the first level of keys to leave
Array
(
[107] => Array
(
[id] => 107
[name] => About Us
[indexID] => about
[level] => 0
[parent] => 0
)
[109] => Array
(
[id] => 109
[name] => Home
[indexID] => index
[level] => 0
[parent] => 0
)
}
etc etc
Assuming $data is the above array I went with:
foreach ($data as $k => $v) {
if ($v['parent'] == 0) {
$bc[$v['indexID']][0]['name'] = $v['name'];
$bc[$v['indexID']][0]['indexID'] = $v['indexID'];
}
else {
$nextParent = $v['parent'];
$currentIndexID = $v['indexID'];
$currentName = $v['name'];
$bc[$v['indexID']][0]['name'] = $currentName;
$bc[$v['indexID']][0]['indexID'] = $currentIndexID;
for($i=1;$i<=$level;$i++) {
foreach ($data as $a => $b) {
if ($a == $nextParent) {
$nextParent = $b['parent'];
$bc[$v['indexID']][$i]['name'] = $b['name'];
$bc[$v['indexID']][$i]['indexID'] = $b['indexID'];
}
}
}
}
}

Manipulate a Multi-Multi-Dimensional PHP Array into a nice Multi-Dimensional Array

I know this is considered a somewhat basic PHP Array question but i'm running on 35 hours no sleep and I really just need to finish this up as quickly as posibble so I can get to sleep...sorry just being honest!
In PHP I have this variable $design_values
If I print_r($design_values); this ARRAY it spits out what is show below. It is "Desing" database records.
In this case there is 2 Design records which make up the first 2 Array keyys the 0 and 1
In the application there can be any number of Designs from 0 up to any number.
Now under the 2 Design Records are 24 more Array keys for each of the 2 Design Arrays.
These 24 Array keys are numbered 0 to 23.
Now under each of the 24 Array keys, is 2 keys. One named name and the other named value.
I need to take the Array $design_values and create a new Array of that array. The new Array should be formatted much better amd easy to work with.
So the name and value keys should make up a key => value. The New array should look more like this....
The reason the current Array is a complete nightmare is because that is the Format I get it in from an existing library which returns this Data from an API call.
If someone can help me to manipulate this Array into the desired Array I will be grateful! I have been messing with it for 2 hours with no luck.
Desired New Array Format :
Array
(
[0] => Array
(
['assigned_user_name'] => 'Jason Administrator',
['modified_by_name'] => 'Jason Administrator',
['created_by_name'] => 'Jason Administrator',
['id'] => '4c5c3c08-2b14-9f9c-6cee-542c56cac7b1',
['date_entered'] => '2014-10-01 19:29:32',
....continued for all 24 record items
),
[1] => Array
(
['assigned_user_name'] => 'Jason Administrator',
['modified_by_name'] => 'Jason Administrator',
['created_by_name'] => 'Jason Administrator',
['id'] => '4c5c3c08-2b14-9f9c-6cee-542c56cac7b1',
['date_entered'] => '2014-10-01 19:29:32',
....continued for all 24 record items
)
)
Current Array Format :
Array
(
[0] => Array
(
[0] => Array
(
[name] => assigned_user_name
[value] => Jason Administrator
)
[1] => Array
(
[name] => modified_by_name
[value] => Jason Administrator
)
[2] => Array
(
[name] => created_by_name
[value] => Jason Administrator
)
[3] => Array
(
[name] => id
[value] => 4c5c3c08-2b14-9f9c-6cee-542c56cac7b1
)
[4] => Array
(
[name] => name
[value] => test
)
[5] => Array
(
[name] => date_entered
[value] => 2014-10-01 19:29:32
)
[6] => Array
(
[name] => date_modified
[value] => 2014-10-01 19:29:32
)
[7] => Array
(
[name] => modified_user_id
[value] => 1
)
[8] => Array
(
[name] => created_by
[value] => 1
)
[9] => Array
(
[name] => description
[value] =>
)
[10] => Array
(
[name] => deleted
[value] => 0
)
[11] => Array
(
[name] => assigned_user_id
[value] => 1
)
[12] => Array
(
[name] => chann_channelqms_id_c
[value] =>
)
[13] => Array
(
[name] => channelqms
[value] =>
)
[14] => Array
(
[name] => design_name
[value] =>
)
[15] => Array
(
[name] => design_number
[value] =>
)
[16] => Array
(
[name] => overall_height
[value] =>
)
[17] => Array
(
[name] => overall_width
[value] =>
)
[18] => Array
(
[name] => show_to_customer
[value] => 1
)
[19] => Array
(
[name] => uploadfile
[value] => 2014-09-29_21-57-50.png
)
[20] => Array
(
[name] => nam_channelletterqms_nam_channelletterqms_designs_name
[value] => Test
)
[21] => Array
(
[name] => price_c
[value] =>
)
[22] => Array
(
[name] => shipping_c
[value] =>
)
[23] => Array
(
[name] => totalprice_c
[value] =>
)
)
[1] => Array
(
[0] => Array
(
[name] => assigned_user_name
[value] => Jason Administrator
)
[1] => Array
(
[name] => modified_by_name
[value] => Jason Administrator
)
[2] => Array
(
[name] => created_by_name
[value] => Jason Administrator
)
[3] => Array
(
[name] => id
[value] => 86f21f44-4b21-1826-3592-542c59e4be66
)
[4] => Array
(
[name] => name
[value] => fdtgrfdhg
)
[5] => Array
(
[name] => date_entered
[value] => 2014-10-01 19:41:54
)
[6] => Array
(
[name] => date_modified
[value] => 2014-10-19 19:30:45
)
[7] => Array
(
[name] => modified_user_id
[value] => 1
)
[8] => Array
(
[name] => created_by
[value] => 1
)
[9] => Array
(
[name] => description
[value] =>
)
[10] => Array
(
[name] => deleted
[value] => 0
)
[11] => Array
(
[name] => assigned_user_id
[value] => 1
)
[12] => Array
(
[name] => chann_channelqms_id_c
[value] =>
)
[13] => Array
(
[name] => channelqms
[value] =>
)
[14] => Array
(
[name] => design_name
[value] => design name
)
[15] => Array
(
[name] => design_number
[value] => 313
)
[16] => Array
(
[name] => overall_height
[value] => 22
)
[17] => Array
(
[name] => overall_width
[value] => 22
)
[18] => Array
(
[name] => show_to_customer
[value] => 1
)
[19] => Array
(
[name] => uploadfile
[value] => 2014-09-29_21-57-50.png
)
[20] => Array
(
[name] => nam_channelletterqms_nam_channelletterqms_designs_name
[value] => Test
)
[21] => Array
(
[name] => price_c
[value] =>
)
[22] => Array
(
[name] => shipping_c
[value] =>
)
[23] => Array
(
[name] => totalprice_c
[value] =>
)
)
)
If you can't change it at the source then here is one way (PHP >= 5.5.0 needed for array_column):
foreach($design_values as $key => $values) {
$result[$key] = array_combine(
array_column($values, 'name'),
array_column($values, 'value'));
}
Or possibly, and easier:
foreach($design_values as $key => $values) {
$result[$key] = array_column($values, 'value', 'name');
}
Our use the PHP Implementation of array_column
You should probably create the array you want when making the first array, but if you don't have control over that and just want to conver then something like this should work:
$newArray = array();
foreach($oldArray as $row){
$tmp = array();
foreach($row as $values){
$tmp[$values['name']] = $values['value'];
}
$newArray[] = $tmp;
}
print_r($newArray);

Sort multidimension array in php by more than two fields [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 8 years ago.
I want to sort array by two fields. I mean to say I have an array like :-
Array
(
[0] => Array
(
[name] => abc
[url] => http://127.0.0.1/abc/img1.png
[count] => 69
[img] => accessoire-sets_1.jpg
)
[1] => Array
(
[name] => abc2
[url] => http://127.0.0.1/abc/img12.png
[count] => 73
[img] =>
)
[2] => Array
(
[name] => abc45
[url] => http://127.0.0.1/abc/img122.png
[count] => 15
[img] => tomahawk-kopen_1.png
)
[3] => Array
(
[name] => zyz
[url] => http://127.0.0.1/abc/img22.png
[count] => 168
[img] =>
)
[4] => Array
(
[name] => lmn
[url] => http://127.0.0.1/abc/img1222.png
[count] => 10
[img] =>
)
[5] => Array
(
[name] => qqq
[url] => http://127.0.0.1/abc/img1222.png
[count] => 70
[img] =>
)
[6] => Array
(
[name] => dsa
[url] => http://127.0.0.1/abc/img1112.png
[count] => 43
[img] =>
)
[7] => Array
(
[name] => wer
[url] => http://127.0.0.1/abc/img172.png
[count] => 228
[img] =>
)
[8] => Array
(
[name] => hhh
[url] => http://127.0.0.1/abc/img126.png
[count] => 36
[img] =>
)
[9] => Array
(
[name] => rrrt
[url] => http://127.0.0.1/abc/img12.png
[count] => 51
[img] =>
)
[10] => Array
(
[name] => yyy
[url] => http://127.0.0.1/abc/img12.png
[count] => 22
[img] =>
)
[11] => Array
(
[name] => cxz
[url] => http://127.0.0.1/abc/img12.png
[count] => 41
[img] =>
)
[12] => Array
(
[name] => tre
[url] => http://127.0.0.1/abc/img12.png
[count] => 32
[img] =>
)
[13] => Array
(
[name] => fds
[url] => http://127.0.0.1/abc/img12.png
[count] => 10
[img] =>
)
)
array WITHOUT images (field "img" )should always be placed underneath array WITH images. After this there will be sorted on the amount of products (field count) in the array.
Means I have to show sort array first on the basis of img then count.
I am using
usort( $childLinkCats, 'sortempty' );`
function sortempty( $a, $b ) {
return empty( $a['img'] );
}
it will show array with image value above the one who contains null value.
and to sort through count Im using
usort($childLinkCats, "_sortByCount");
function _sortByCount($a, $b) {
return strnatcmp($a['count'], $b['count']);
}
It will short by count
But I am facing problem that only 1 working is working at a time, but I have to use both, please help me.
Write a function that calls both comparison functions:
usort($childLinkCats, function($a, $b) {
if (empty($a['img']) == empty($b['img'])) {
return _sortByCount($a, $b);
} else {
return sortempty($a, $b);
}
});
You need to ensure that _sortByCount and sortempty return proper values. Comparison functions must return -1, 0, or 1, not true or false.

PHP array_merge not doing exactly what i need it to do

Ok so here is my first array:
(
[1] => Array
(
[27] => Array
(
[product_id] => 27
[type] => hardware
[step_number] => 1
)
[372] => Array
(
[product_id] => 372
[type] => hardware
[step_number] => 1
)
[92] => Array
(
[product_id] => 92
[type] => hardware
[step_number] => 1
)
)
[2] => Array
(
[335] => Array
(
[product_id] => 335
[type] => hardware
[step_number] => 2
)
[62] => Array
(
[product_id] => 62
[type] => hardware
[step_number] => 2
)
[356] => Array
(
[product_id] => 356
[type] => hardware
[step_number] => 2
)
)
and here is my second array
(
[1] => Array
(
[655] => Array
(
[product_id] => 655
[type] => optional
[step_number] => 1
)
[54] => Array
(
[product_id] => 54
[type] => optional
[step_number] => 1
)
[554] => Array
(
[product_id] => 554
[type] => optional
[step_number] => 1
)
)
[2] => Array
(
[33] => Array
(
[product_id] => 33
[type] => optional
[step_number] => 2
)
[612] => Array
(
[product_id] => 612
[type] => optional
[step_number] => 2
)
[5] => Array
(
[product_id] => 5
[type] => optional
[step_number] => 2
)
)
[3] => Array
(
[444] => Array
(
[product_id] => 444
[type] => optional
[step_number] => 3
)
[6] => Array
(
[product_id] => 6
[type] => optional
[step_number] => 3
)
[53] => Array
(
[product_id] => 53
[type] => optional
[step_number] => 3
)
)
Basically what i need is the second array appended to the end of the first array with the keys of the first array preserved the keys and changing the step_number to the new key so the final keys looks like
(
[1] => Array
(
[27] => Array
(
[step_number] => 1)
....
[2] => Array
(
[335] => Array
(
[step_number] => 2)
....
[3] => Array
(
[655] => Array
(
[step_number] => 3)
....
[4] => Array
(
[33] => Array
(
[step_number] => 4)
....
[5] => Array
(
[444] => Array
(
[step_number] => 5)
....
but when i do
$all = array_merge($first, $second);
the keys are
(
[0] => Array
[1] => Array
[2] => Array
[3] => Array
[4] => Array
Is that possible to do....
Try array_merge_recursive .. http://php.net/array_merge_recursive
This is also from the manual on array_splice if you're just looking to append your 2nd array onto the first (http://php.net/manual/en/function.array-push.php):
array_splice($first, count($first), 0, $second);
Iterating over the first set of keys, then using the Union array operator should do the trick.
//$first = array(...);
//$second = array(...);
foreach ($second as $key => $value)
{
if (!isset($first[$key]))
{
$first[$key] = array();
}
$first[$key] += $value;
}

Categories