Welcome to WebmasterWorld Guest from 54.204.253.227

Forum Moderators: coopster & jatar k

Sorting multidimensional array

     
12:49 am on Dec 23, 2016 (gmt 0)

New User

Top Contributors Of The Month

joined:Aug 21, 2016
posts:12
votes: 0


I have a string made up of different parts that I need to reorder:

$string = 'coke:brown:120;water:clear:0;milk:white:90';

The string comprises of fields separated by a semicolon, with sub-parts separated by a colon.

I'm trying to explode the string into a multidimensional array sorted by the value in the third sub-part.

I have:

$new = array();
$temp = explode(';', $string);
foreach($temp as &$subpart) $new[] = explode(':', $subpart);

Its not very elegant, but it gets the data into a multidimensional array, but I just don't know how to sort it. Any tips?
4:35 pm on Jan 3, 2017 (gmt 0)

Administrator

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:July 31, 2003
posts:12547
votes: 2


A quick search over the WebmasterWorld forums here turns up some examples:

Help sorting a multidimensional array [webmasterworld.com]
multisort unknown N levels multidimensional array [webmasterworld.com]
5:06 pm on Jan 9, 2017 (gmt 0)

Senior Member from MZ 

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 9, 2005
posts: 828
votes: 0


I do not understand why are you using by-reference in foreach loop. Anyway, you can use usort() function to send all the values of your array to a custom function that will sort it. See the following,

$string = 'coke:brown:120;water:clear:0;milk:white:90';
$new = array();
$temp = explode(';', $string);
foreach($temp as $subpart) $new[] = explode(':', $subpart);
echo "<pre>";
print_r($new);
function sortIT($a,$b){
return $a[2] - $b[2];
}
usort($new, "sortIT");
print_r($new);


here is the working demo [fastcreators.com ]
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members