我需要按照另一个数组内容的确切顺序对关联阵列进行排序。 阵列通过2个单独的SQL重新测量(下面说明)检索。这些请求不能仅合并到一个请求,因此我必须将第二个数组对第一个请求进行分类。 这些是阵列:
#Array which contains the id's in needed order
$sorting_array = array(1,2,3,8,5,6,7,9,11,10...);
#Array which contains the values for the id's, but in order of "id" ASC
$array_to_sort = array(
array("id" => "1", "name" => "text1", "help" => "helptxt2");
array("id" => "2", "name" => "text2", "help" => "helptxt2");
);
sql-queries:$ satering_array的sql-ouery:
(db-field'conf'被设置为“文本”,也许这是我的问题,以便我必须先爆炸并爆炸,然后才能将条目用于下一个查询。)
$result = sql_query("select conf from config where 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, so I count them down here
$sorting_array = implode(',', $new);
$result = sql_query("SELECT id, name, helptxt
FROM table
WHERE id IN ($sorting_array)
AND language='english'");
while ($array_to_sort[] = mysql_fetch_array ($result, MYSQL_ASSOC)) {}
array_pop($array_to_sort);#deleting the last null entry
我可以访问$ array_to_sort,如下所示,以一个:
查看内容。 (如果下面的线与上面的数组不匹配,则比我混合了。但是,下面的行是带来内容的内容)
echo $array_to_sort[0]["id"];
echo $array_to_sort[0]["name"];
echo $array_to_sort[0]["helptxt"];
while(list(,$array_to_sort) = each($sorting_array)){
$i++;
echo $array_to_sort . "<br>";
}
取得您的结果:
$result = mysql_query("SELECT id, name, helptxt
FROM table
WHERE id IN ($sorting_array)
AND language='english'");
$array_to_sort = array();
while ( ($row = mysql_fetch_assoc($result)) !== false ) {
// associate the row array with its id
$array_to_sort[ $row[ "id" ] ] = $row;
}
要按顺序显示它们:
$sorting_array
foreach ( $sorting_array as $id ) {
// replace the print_r with your display code here
print_r( $array_to_sort[ $id ] );
}
这很难说,因为这里发生了很多事情,如果您提出几个简单的问题并弄清楚自己如何使答案结合在一起,您将来可能会得到更好的回答。 您最好的选择是将您可以将这些查询结合在一起的SQL Tablessuch重组。 您可以在PHP中做您要问的事情,但是它比在MySQL中做的要慢,而且要复杂得多。
做您要问的事情(php的速度很慢):
$sorting_array
在这种情况下,我倾向于做的是首先将数组与数据重新排列。因此,钥匙代表IDS在您的情况下:
$result = mysql_query("select conf from config where user='me'", $dbi);
$conf = mysql_fetch_array($result, $dbi);
$temp = explode(',', $conf[0]);
// limit to 30 ids
$new = array();
// no need to do this manually, use a loop
for ( $i = 0; $i < 30; ++$i )
$new[] = $temp[ 0 ];
$sorting_array = implode(',', $new);
$sorted = array();
foreach ( $sorting_array as $id )
{
foreach ( $array_to_sort as $values )
{
if ( $values['id'] == $id )
{
$sorted[] = $values;
break;
}
}
}
该解决方案非常有效,因为您只有2个foreach循环。
Edit!!!
我再也无法编辑问题了,我只是想以这种方式陈述我的解决方案:
$array_to_sort_ids = array();
foreach ($array_to_sor as $item)
{
$array_to_sort_ids[$item['id']] = $item;
}
$array_sorted = array();
foreach ($sorting_array as $id)
{
$array_sorted[] = $array_to_sort_ids[$id];
}
将做到这一点。它以您想要的方式订购结果,即使这意味着1,4,2,3,9,7,...
有时候,当您知道在哪里看时,这很容易。 再次感谢!!!