I’ve got three strings generated from a long process of combined queries and file reads, each related to the other.
Example:
$versions = "1 2 5 4 10 6 8 7 3 9";
$weights = "50.2 60.5 35 10 15.98 60 50 60.1 70 75";
$ids = "512 318 112 326 155 191 977 961 943 441";
I would like to sort them in ascending order according to version number.
Example result:
$versions = "1 2 3 4 5 6 7 8 9 10";
$weights = "50.2 60.5 70 10 35 60 60.1 50 75 15.98";
$ids = "512 318 943 326 112 191 961 977 441 155";
My question is: is there a more efficient way of doing this than I am currently doing it?
Note that these strings can become big, largest I’ve seen so far is ~600 different versions
I do the following:
- explode strings
- copy arrays with version number as keys
- sort arrays by keys
- implode strings back
Here’s the code and a live example:
$versions = "1 2 5 4 10 6 8 7 3 9";
$weights = "50.2 60.5 35 10 15.98 60 50 60.1 70 75";
$ids = "512 318 112 326 155 191 977 961 943 441";
$a_versions = explode(" ", $versions);
$a_weights = explode(" ", $weights);
$a_ids = explode(" ", $ids);
$s_versions = array();
$s_weights = array();
$s_ids = array();
//set keys to correspond to version number
foreach($a_versions as $key => $ver){
$s_versions[$ver] = $a_versions[$key];
$s_weights[$ver] = $a_weights[$key];
$s_ids[$ver] = $a_ids[$key];
}
//sort according to keys
ksort($s_versions, SORT_NUMERIC);
ksort($s_weights, SORT_NUMERIC);
ksort($s_ids, SORT_NUMERIC);
//implode back
$versions = implode(" ", $s_versions);
$weights = implode(" ", $s_weights);
$ids = implode(" ", $s_ids);
echo "
<pre>
$versions
$weights
$ids
</pre>
";
/*==========
Results
1 2 3 4 5 6 7 8 9 10
50.2 60.5 70 10 35 60 60.1 50 75 15.98
512 318 943 326 112 191 961 977 441 155
==========*/
Performance increase #1:
Replacing the foreach loop with array_combine might give a little performance gain. – svens
Indeed it did, according to a simple unit test, it’s about 11-15% faster.
This is the best I could find:
See:
http://codepad.viper-7.com/flcvnO
for a comparison of what I tested (including you initial code and the one with array_combine)