Save Column Name as item in another Column

Asked

Viewed 41 times

0

Next, I have a table with several values and I need to compare the values of several columns, I did this with PHP and managed to separate the highest value, follows the code:

    while($aux = mysqli_fetch_array($query))
{


    $cb = $aux['cb'];
    $rb = $aux['rb'];
    $lb = $aux['lb'];
    $rwb = $aux['rwb'];
    $lwb = $aux['lwb'];
    $cdm = $aux['cdm'];
    $cm = $aux['cm'];
    $rm = $aux['rm'];
    $lm = $aux['lm'];
    $cam = $aux['cam'];
    $cf = $aux['cf'];
    $rf = $aux['rf'];
    $lf = $aux['lf'];
    $rw = $aux['rw'];
    $lw = $aux['lw'];
    $st = $aux['st'];
    $Maior = 0;
    $arr = array($cb,$rb,$lb,$rwb,$lwb,$cdm,$cm,$rm,$lm,$cam,$cf,$rf,$lf,$rw,$lw,$st);
    foreach ($arr as &$value) {
        if($value > $Maior) {


            $total = $value;

        }
        $Maior = $value;

    }


    unset($value);    
}
    echo $total;             

What I’m not able to think logically is how to do for example, if cf is the highest, how to assign a variable the text 'cf' and with that I would make an Insert in a table, in that filter I know that cf is the highest.

  • Honestly, your code is a bit messy, there is something there that doesn’t even need, ta missing a lot of information: What are these variables $cb, $rb, ...? What is the $total and $maior? Why unset($value);? What is the purpose of the code? Maybe what you want can be done directly in SQL

  • are the values sought by the select that is above the while, the goal is to take the higher value, when found instead of saving the value I want to save the column name, for example "CF"

2 answers

0

You could search the return array itself and not create a new array. Dai would have the reference of which column took the largest.

$maior = 0;
$colunaMaior = '';
while($aux = mysqli_fetch_array($query))
{
  foreach($aux as $key => $value){
     if($value > $maior){
        $maior = $value;
        $colunaMaior = $key;
     }
  }

}

0


With these 3 commands you get what you want:

  • Compact- creates an array containing variables and their values
  • max - locates the highest value
  • array_search - looks for a value in an array and returns its corresponding key if found

    $cb = $aux['cb'];
    $rb = $aux['rb'];
    $lb = $aux['lb'];
    $rwb = $aux['rwb'];
    $lwb = $aux['lwb'];
    $cdm = $aux['cdm'];
    $cm = $aux['cm'];
    $rm = $aux['rm'];
    $lm = $aux['lm'];
    $cam = $aux['cam'];
    $cf = $aux['cf'];
    $rf = $aux['rf'];
    $lf = $aux['lf'];
    $rw = $aux['rw'];
    $lw = $aux['lw'];
    $st = $aux['st'];
    
    $arr = array("cb","rb","lb","rwb","lwb","cdm","cm","rm","lm","cam","cf","rf","lf","rw","lw","st");
    
    $result = compact($arr);
    
    $maior =(max($result));
    
    $chave = array_search(max($result), $result);
    

see example in ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.