peace_love
peace_love

Reputation: 6471

How can I sort by variable within a foreach loop (php)?

in my for each loop I want to sort my options by the value of my variable $total resp. by the 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>

Is this possible? Thank you very much!

Upvotes: 0

Views: 568

Answers (1)

Harshit
Harshit

Reputation: 5157

In your for loop do something like this

$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;
}

Upvotes: 1

Related Questions