I encountered a problem yesterday (that flowed into today) dealing with associative arrays and how to sort them. My problem was that I had to merge two associative arrays, then sort them based on a value in the second level array.
Here is an example:
$my_array1 = array(
    array(
         ‘id’ => ’1′,
         ‘name’ => ‘tom’
    ),
    array(
         ‘id’ => ’2′,
         ‘name’ => ‘harry’
    )
);
$my_array2 = array(
    array(
         ‘id’ => ’5′,
         ‘name’ => ‘dick’
    ),
    array(
         ‘id’ => ’4′,
         ‘name’ => ‘bob’
    )
);
$merged_array = array_merge( $my_array1 , $my_array2 );
Now, this part worked fine and dandy, except when I went to sort the merged array. I was using usort and a function I had found on the internet:
function arfsort( $a, $fl ){
 $GLOBALS['__ARFSORT_LIST__'] = $fl;
 usort( $a, ‘arfsort_func’ );
 return $a;
}// extended to allow sort direction per field sorted against
function arfsort_func( $a, $b ){
 foreach( $GLOBALS['__ARFSORT_LIST__'] as $f ) {
  switch ($f[1]) { // switch on ascending or descending value
   case “d”:
    $strc = strcmp( strtolower($b[$f[0]]), strtolower($a[$f[0]]) );
    if ( $strc != 0 ){
     return $strc;
    }
   break;
   default:
    $strc = strcmp( strtolower($a[$f[0]]), strtolower($b[$f[0]]) );
    if ( $strc != 0 ){
     return $strc;
    }
   break;
  }
 }
 return 0;
}
What was happening was that the usort was not working. So, I started to think about ways to get around the problem of the usort. My first thoughts were some way to work around it in PHP, so I went and asked a colleague if she new of any way to sort associative arrays in the fashion I needed to. Her first comment was to try and do something in the SQL query before you ever get the data. We talked for a bit and I got this bright idea. I could use the handy IN operator from MySQL. First, I would have to build a string of IDs for the database, then use the IN operator to query for just those IDs in the database. For example:
$my_array1 …. (like above)
$my_array2 …. (like above)$merged_array = array_merge( $my_array1 , $my_array2 );
foreach($merged_array as $m){
    $merge_list[] = $m['id'];
}$list_for_query = implode(‘,’,$merge_list);
$query = “SELECT * FROM my_table WHERE id IN ($merge_list) ORDER BY name”;
So, to explain the above code it goes something like this:
- Make the arrays (mine were two different queries that I needed to merge together)
- Note: the arrays just need to have the row ID in them. No sense in wasting time getting all the columns from the table
- Merge the arrays (they need to be identical)
- Make the associative arrays a one level array
- Implode the list so there are commas separating the ID values
- Query using those ID values and use ORDER BY to get the correct sorting
Lo and behold, it works. It does just what I want, and I don’t have to fuss about using a custom usort. Hopefully this will help someone else down the road so you don’t waste your time like I did.
ÂÅ
