I’m surprised that there isn’t already an answer for this… it suggests to me that I’m doing something fundamentally wrong. Or everyone else is.
Let’s say I have an array of possibly repeating values that were sorted client-side coming in as a POST request and the goal is to return a result-set from MySQL indexed by those values and in the same order as those values and preserving the redundancies!!!
So, if the values were: 1,2,3,2,3,4,5,5,5
The desired result is:
+----+-------+
| id | value |
+----+-------+
| 1 | one |
| 2 | two |
| 3 | three |
| 2 | two |
| 3 | three |
| 4 | four |
| 5 | five |
| 5 | five |
| 5 | five |
+----+-------+
The code below seems to work, but Christ, seriously? I have to abuse array_intersect() and have two different loops, one of them nested, just to make a simple result set get ordered and repeated in the same pattern as the input array? This can’t be how it’s really supposed to be done.
function repQuery($inids,$incol,$querystring,$emptyval = "NULL"){
# incol is the name of a column in the query
# inids is an array within which the value of incol must be found
# querystring is a query of the form...
# "select FOO from BAR where %s in (%s) BLAH BLAH BLAH"
# The first %s will be replaced by $incol and the second by $inids
$qq = mysql_query(sprintf($querystring,$incol,implode(",",$inids))) or die(mysql_error());
$nf = mysql_num_fields($qq); $dummyrow = array();
for($ii = 0; $ii < $nf; $ii+= 1){
$dummyrow[mysql_field_name($qq,$ii)] = $emptyval;
};
$out = array_fill(0,count($inids),$dummyrow);
while($rr = mysql_fetch_assoc($qq)){
foreach(array_keys(array_intersect($inids,array($rr[$incol]))) as $ii) {
$out[(int)$ii] = $rr;
}
}
return $out;
}
My question is: is there some accepted pattern or PHP array command or something else that I’m overlooking? In R the above would be a one-liner.
While it would be awesome if it were a feature in MySQL, I don’t think there is a way to use
ORDER BYwith a repeating pattern (you can get a “custom pattern” viaORDER BY FIELD(), but not quite there).I’m not sure about any special methods in PHP just for this, but using a temporary array might be able to reduce the headache:
This will place every SQL result (one for each ID) in the
$tmpResultsarray using the row’s ID as the array’s index. The next step is to iterate through the$inidslist, which contains the pattern to replicate, and to insert the corresponding record-result into the$outarray.