Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Sorting multidimensional array

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

New User

Top Contributors Of The Month

joined:Aug 21, 2016
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)


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

joined:July 31, 2003
votes: 3

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: 837
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>";
function sortIT($a,$b){
return $a[2] - $b[2];
usort($new, "sortIT");

here is the working demo [fastcreators.com ]