我试图按我的计算值对mysql数据进行排序.我知道rsort(),sort(),但是我无法在foreach之外对它们进行单独排序,因为它将不一致.当我只想按百分比对它们进行排序时,我有三个数组需要保持一致.我怎样才能做到这一点?欣赏.
<?php
//certain mysql connection code hide because it's not relative to this question.
foreach ($rows as row) {
$member_id=row['user_id'];
$count=row['count'];
$user_link[]=bp_core_get_user_domain( $member_id );
$user_displayname[]=bp_core_get_user_displayname( $member_id );
$combine_count[]=round(($count/$count_user_diff)*100);//calculate value
}//foreach
//how can I sort data here since I have three arrays together.
for ($i=0; $i<7; $i++){
echo "<a href='$user_link[$i]'><div>$user_avatar[$i]<ul>$combine_count[$i]</ul></div></a>";
}
?>
解决方法:
维护三个阵列之间连接的一种方法是使用关联阵列.如果成员ID是唯一的,则将其用于每个数组的索引.例如:
<?php
// $unique_id = 0; // in case $member_id is not unique
foreach ($rows as $row) {
$member_id = $row['user_id'];
$count = $row['count'];
// use $member_id as index to align arrays
$user_link[$member_id]=bp_core_get_user_domain( $member_id );
$user_displayname[$member_id]=bp_core_get_user_displayname( $member_id );
//$user_avatar[$member_id]=bp_core_get_user_avatar( $member_id ); // missing avatar array?
$combine_count[$member_id]=round(($count/$count_user_diff)*100);
//$unique_id++;
}
arsort($combine_count); // maintain index, descending order
// $combine_count = array_slice($combine_count, 0, 7, true); // top 7
// slice array if you only want the top 7 as the question implies
// loop over $combine_count array
foreach ( $combine_count as $member_id => $c_count ) {
echo "<a href='$user_link[$member_id]'><div>$user_avatar[$member_id]<ul>$combine_count[$member_id]</ul></div></a>";
}
?>
如果成员ID可能在结果集中出现多次,则只需实例化一个变量(例如本例中的$unique_id),然后对每个结果进行递增,然后将其用于所有三个数组的索引而不是$member_id.
另外,如果您只想显示前几个结果,并且想要维护完整的$combine_count数组以备后用,则还可以执行以下操作:
arsort($combine_count); // maintain index, descending order
// loop over $combine_count array
$cc = 0; // start counter
foreach ( $combine_count as $member_id => $c_count ) {
echo "<a href='$user_link[$member_id]'><div>$user_avatar[$member_id]<ul>$combine_count[$member_id]</ul></div></a>";
$cc++; // increment counter
if ( 7 <= $cc ) { break; } // break out of loop if counter is greater than or equal to 7
}
您是否在代码中缺少某些$,特别是在行中?我加了我以为他们不见了的地方.好像您缺少$user_avatar数组.还是我错过了什么?