Jump to content

Sort 2-D or Multi-Dimensional Array?


scienceskillz

Recommended Posts

Hi. I know sort($array) will sort a 1-D array. However, is there a built-in function like that to sort multidimensional array by one of the dimensions?

 

for example

 

$myarray = array();

 

$myarray['fruits'] = ['apple','orange','banana'];

$myarray['expireDate'] = ['jan','march','february'];

 

I want to sort fruits and expireDate based on expireDate.. so this pseudo function would return:

 

somespecialsortfunction($myarray,'expireDate')

 

$myarray['fruits'] = ['apple','banana','orange'];

$myarray['expireDate'] = ['jan','february','march'];

 

I realize the dates are just month strings but imagine I have actual dates inside the 'expireDate' array ....

 

I hope I've made this clear enough...

 

Thanks!

 

SS

Link to comment
https://forums.phpfreaks.com/topic/185799-sort-2-d-or-multi-dimensional-array/
Share on other sites

How would such a function work? There isn't one that I'm aware of if what I think you're wanting is correct. However, as with most things like this, it's generally only a matter of a few lines of code to implement such a function yourself.

Hi, Well sure I guess I could implement something like this myself but I just figured maybe something was already out there.

 

What I want is the following:

 

given an array $arr = array('2','2','hi');

 

array_unique($arr)... would make $arr = array('2','hi');

 

but.. what I require is multi-dimension application.

 

So... $arr['somekey'] = array('2','2','hi');

$arr['someotherkey'] = array('blah','blah2','blah3');

 

array_unique($arr['somekey'],$arr['someotherkey'])...

 

Would make...

 

$arr['somekey'] = array('2','hi');  and $arr['someotherkey'] = array('blah','blah3');

 

Hmm.. that seems like it just makes each array unique but not necessarily re-defines each array based on the uniqueness of one... for example..

 

$parameters[] = array('1','2','1');

$parameters[] = array('hi','yo','bla');

 

 

$newArray = array_map('array_unique', $parameters);

var_dump($newArray);

 

outputs:

 

array(2) { [0]=>  array(2) { [0]=>  string(1) "1" [1]=>  string(1) "2" } [1]=>  array(3) { [0]=>  string(2) "hi" [1]=>  string(2) "yo" [2]=>  string(3) "bla" } }

 

but I want it to output:

 

array(2) { [0]=>  array(2) { [0]=>  string(1) "1" [1]=>  string(1) "2" } [1]=>  array(3) { [0]=>  string(2) "hi" [1]=>  string(2) "yo" } }

 

because 1 is duplicated and it needs to redefine the second array accordingly to not include 'bla'

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.