PHP Sorting associative-array by other array -
i need sort associative-array in exact order of content of array. arrays retrieve 2 separate sql-requests (stated below). requests not combined 1 request, have sort second array order of first one.
these arrays:
#array contains id's in needed order $sorting_array = array(1,2,3,8,5,6,7,9,11,10...);  #array contains values id's, in order of "id" asc $array_to_sort = array(               array("id" => "1", "name" => "text1", "help" => "helptxt2");               array("id" => "2", "name" => "text2", "help" => "helptxt2"); );   the sql-queries:
 sql-ouery $sorting_array: 
(the db-field 'conf' setup "text", maybe problem have first explode , implode entries before use next query.)
$result = sql_query("select conf config user='me'", $dbi); $conf = sql_fetch_array($result, $dbi); $temp = explode(',', $conf[0]);  $new = array($temp[0], $temp[1], $temp[2], $temp[3],$temp[4],              $temp[5], $temp[6], $temp[7], $temp[8], $temp[9],              $temp[10], ...);#array has max 30 entries, count them down here $sorting_array = implode(',', $new);   sql-ouery $array_to_sort:
$result = sql_query("select id, name, helptxt                    table                     id in ($sorting_array)                    , language='english'");  while ($array_to_sort[] = mysql_fetch_array ($result, mysql_assoc)) {} array_pop($array_to_sort);#deleting last null entry   i access $array_to_sort follows see content 1 one:
 (if lines below don't match array above, mixed up. however, lines below brings content)
echo $array_to_sort[0]["id"]; echo $array_to_sort[0]["name"]; echo $array_to_sort[0]["helptxt"];   but sorted "id" asc, need sorting in $sorting_array. tried things with:
while(list(,$array_to_sort) = each($sorting_array)){ $i++; echo $array_to_sort . "<br>"; }   which brings id's in correct order, not content. i'm bit confused, tried many things, ended in giving me same results.
 maybe sql-query done in 1 step, didn't brought work. results searches showed how sort asc or desc, not want.
furthermore must confess i'm relative new php , mysql.
 1 of bring me on track.
 many in advance.
to fetch results:
$result = mysql_query("select id, name, helptxt   table    id in ($sorting_array)   , language='english'"); $array_to_sort = array(); while ( ($row = mysql_fetch_assoc($result)) !== false ) {   // associate row array id   $array_to_sort[ $row[ "id" ] ] = $row; }   to display them in order of $sorting_array:
foreach ( $sorting_array $id ) {   // replace print_r display code here   print_r( $array_to_sort[ $id ] ); }   and bonus tip code fetching $sorting_array:
$result = mysql_query("select conf config user='me'", $dbi); $conf = mysql_fetch_array($result, $dbi); $temp = explode(',', $conf[0]); // limit 30 ids $new = array(); // no need manually, use loop ( $i = 0; $i < 30; ++$i )   $new[] = $temp[ 0 ]; $sorting_array = implode(',', $new);      
Comments
Post a Comment