I do not understand the array in php

1
<?php 

$empleados = array(
    array('Powell, Alfredo','Administrativo',5500),
    array('Pérez, Verónica','Administrativo',5200),
    array('Goldstein, Juan','Recursos Humanos',6800),
    array('Giaccomo, Walter','Recursos Humanos',6200),
    array('Armani, Luis','Compras',10500),
    array('Sarlanga, Horacio','Administrativo',5500),
    array('Juárez, Alicia','Compras',7500),
    array('Toselli, Agustina','Mantenimiento',5800),
    array('Gómez, Valeria','Sistemas',4700),
    array('Valverde, Emiliano','Recursos Humanos',5800),
    array('Domínguez, Carlos','Mantenimiento',4900),
    array('Carranza, Saúl','Administrativo',9500),
);
$gana_mas = "";
$salario = 0;

foreach ($empleados as $empleado) {
    foreach ($empleado as $valor) {
        if ($valor > $salario) {
            $salario = $valor;
            $gana_mas = $empleado[0]; //NO ENTIENDO ESTO!
        }

    }
        echo '<br />';
        #echo $salario;
}


echo "El salario mas alto es: $salario <br />";
echo "El salario mas alto es de: $gana_mas";

I want to show the name of the worker who charges more, but I do not understand why I have to access it for $ employee [0] and I can not value [0]. As far as I understand $ employee is each row of the array $ employees.

    
asked by Abdullah Awan 03.10.2017 в 14:05
source

2 answers

2

$empleado is an array that contains ('Powell, Alfredo','Administrativo',5500) the first time you enter the foreach loop. I'm drawing it so you can see it better:

$empleado[0] = Powell, Alfredo

$empleado[1] = Administrative

$empleado[2] = 5500

Look here, because you are comparing the salary to all the elements of the array $empleado . In any case, once you have verified that the $valor is the highest salary, take the content of $empleado[0] and assign it to $gana_mas .

$empleado[0] contains the first record of the array, which in this case is "Powell, Alfredo".

The second time you pass through the foreach the value of $empleado will be ('Pérez, Verónica','Administrativo',5200) and the value of $empleado[0] will be "Pérez, Verónica".

    
answered by 03.10.2017 / 14:14
source
0

Let's start with that logic is not correct, since it is comparing the whole array with a numerical value, when we know that the salary is in a fixed position of the array. The most accurate code would be the following:

$gana_mas = "";
$salario = 0;
foreach ($empleados as $empleado) {
    if ($empleado[2] > $salario) {
        $salario = $empleado[2];
        $gana_mas = $empleado[0];
    }

}
    echo '<br />';
    #echo $salario;

The line you mention that you do not understand is simply to store the name of the employee who earns the most money, which is always in position 0 of the array $ employed.

$ employee [2] contains the salary value, so you can also save a foreach.

    
answered by 03.10.2017 в 14:17