0

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!

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

8 Comments

One question: $a now doesn't have the right value. It has now for all options the same value, but in my code above it had the right value.
Thank you! But this doesn't give me the value of $a it gives me a 0and a 1
do I need a multidimensional array for this?
I cannot find what you have changed unfortunately
Have you tried this one ? changed to arsort($total_arr);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.