php - 我如何对多个 mysql foreach 数组进行排序并需要它们在 php 中保持一致?

标签 php mysql arrays sorting

我正在尝试根据我的计算值对 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
}

您是否在代码中遗漏了一些 $,尤其是 row?我添加了我认为他们丢失的地方。看起来您缺少 $user_avatar 数组。还是我遗漏了什么?

关于php - 我如何对多个 mysql foreach 数组进行排序并需要它们在 php 中保持一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28904554/

相关文章:

python - MySql FetchMany 内存问题

mysql - 优化MySQL表结构。需要建议

mysql - 向列添加评论

php - 使用php转换为base64

php - 替换 WooCommerce PayPal 结帐网关插件结帐页面上的图标

php - 使用 Javascript 作为 php 变量返回

python - 执行操作后如何从 numpy 数组中屏蔽 "remove"?

javascript - D3.js 可折叠树 - 展开/折叠中间节点

javascript - 如何在 php 中获取包含一个数组对象的 serializableArray jQuery?

php - 在 Kohana PHP 框架中启用 PECL HTTP