Save the Name of a Column as an item in another Column

1

Next, I have a table with several values and I need to compare the values of several columns, I did this with PHP and I managed to separate the highest value, follow 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 am not able to think in a logical way is how to do for example, if cf is the highest, how to assign a variable the text 'cf' and with that I would do an insert in a table, in that filter I I know that cf is the largest.

    
asked by anonymous 01.11.2018 / 15:46

2 answers

0

With these 3 commands you get what you want:

  • compact - create an array containing variables and their values
  • >
  • max - find the highest value
  • array_search - search 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

    
04.11.2018 / 21:03
0

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

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

}
    
04.11.2018 / 19:59