I have 2 arrays with numerical indices that have the same number of keys and similar but not identical values. $unordered has the unordered data, whereas array $ordered has the data in the proper order. I want to sort $unordered in the same order as $ordered, but keep the percentage values in square brackets from $unordered.
$unordered:
[0] => "Horse [1%]"
[1] => "Cat [5%]"
[2] => "Dog [94%]"
$ordered:
[0] => "Cat"
[1] => "Horse"
[2] => "Dog"
Thanks.
usort
is your go-to sorting function when it comes to complicated things like your example.
Try something like this. Basically, it parses the value from $unordered
, then searches for it in the $ordered
array.
usort($unordered, function($a, $b) use($ordered){
$aVal = explode(' ', $a);
$bVal = explode(' ', $b);
return array_search($aVal[0], $ordered) - array_search($bVal[0], $ordered);
});
DEMO: https://eval.in/184201
Although Rocket Hazmats looks nicer and is better, but you can probably understand this
$array = array();
$array[] = "Horse [5%]"
$array[] ="Cat [1%]";
$array[] ="Dog [99%]";
$ordered = array();
$ordered[] = "Cat";
$ordered[] = "Horse";
$ordered[] = "Dog";
$var = "";
$a = array_fill(0, count($ordered), '');
for($i = 0; $i < count($array); $i++){
preg_match("/[a-zA-z]+/", $array[$i], $var);
for($j = 0; $j < count($ordered); $j++){
if($var[0] == $ordered[$j]) $a[$j] = $array[$i];
}
}
return $a;