Question:
PHP question about sorting arrays and changing indexes?
Justin H
2011-10-03 12:11:33 UTC
I have several arrays in which the value at each index number is associated in each array. I want to sort and renumber the indexes, but I want to maintain the associations.

For example, I start with:
fruit[1] = apple
fruit[2] = orange
fruit[3] = banana

color[1] = red
color[2] = orange
color[3] = yellow

I want to renumber the indexes so I get the following
fruit[1] = apple
fruit[2] = banana
fruit[3] = orange

color[1] = red
color[2] = yellow
color[3] = orange
Three answers:
Jeroonk
2011-10-03 12:25:42 UTC
I see, you are trying to sort the array 'fruit', while keeping the same elements mapped to the ones in 'color'.

What you need is array_multisort, which sorts by the first array and maintains the order of corresponding entries in the second array (or any number of additional arrays).



http://www.php.net/manual/en/function.array-multisort.php



$ar1 = array(3, 1, 4, 2);

$ar2 = array("a", "b", "c", "d");

array_multisort($ar1, $ar2);



Will result in:



$ar1 being 1, 2, 3, 4

$ar2 being "b", "d", "a", "c"
raina_vissora
2011-10-03 12:49:25 UTC
If you want to maintain the associations, you need to actually USE associative arrays.... not just two arrays that you're saying are associated.



You would want to do either:



$fruitArray = array('apple' => 'red', 'orange' => 'orange', 'banana' => 'yellow');



or



$fruitArray = array(1 => array('fruit' => 'apple', 'color' => 'red'), 2 => array('fruit' => 'orange', 'color' => 'orange'), 3 => array('fruit' => 'banana', 'color' => 'yellow'));



Personally, I'd go with the first method... then you can just use the ksort() function on it.
Liz
2011-10-03 12:19:53 UTC
Okay... I don't what the method to your sorting madness is.. Like apple banana orange is alpabetical, so you can re-arrange that with sort() but red, yellow, orange is kinda.. not :) I get they they match the color of the fruit, but the arrays aren't associated, so that hardly matters to the computer.



The answer is in one or more of these functions, and whatever logic you apply to get your results.

in_array();

array_values()

array_merge();


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...