如何在foreach循环(php)中按变量排序?

时间:2015-08-20 10:01:53

标签: php

在我的每个循环中,我想通过变量$total resp的值对我的选项进行排序。由data-total

     <select>
                   <option data-total="0" value="" selected>--</option>
                   <?php 

                    $pdo = Database::connect();


                    $sql = "SELECT  *  FROM table_a;" ;

                    foreach ($pdo->query($sql) as $row) {

                            $a = $row['a'];
                            $number_a = $row['number_a'];               

                            $sql2 = "SELECT  *  FROM table_b WHERE a = '$a';" ;
                            $number_b = 0;

                            foreach ($pdo->query($sql2) as $row2) {
                                $number_b+= $row2['number']; 
                            }

                            $total = $number_a - $number_b;

                            echo '<option data-total="'.$total.'" value="'.$a.'">'.$a;

                    }

                    Database::disconnect();

                        ?>                                                          
     </select>

这可能吗?非常感谢你!

1 个答案:

答案 0 :(得分:1)

在for循环中执行类似这样的操作

$total_arr = array();
foreach ($pdo->query($sql) as $row) {

                            $a = $row['a'];
                            $number_a = $row['number_a'];               

                            $sql2 = "SELECT  *  FROM table_b WHERE a = '$a';" ;
                            $number_b = 0;

                            foreach ($pdo->query($sql2) as $row2) {
                                $number_b+= $row2['number']; 
                            }

                            $total = $number_a - $number_b;
                            $total_arr[$a] = $total;

                    }

arsort($total_arr);
foreach ($total_arr as $key => $val) {
    echo '<option data-total="'.$val.'" value="'.$key.'">'.$key;
}