Home > Back-end >  How can I get the lowest price include the others values from the array
How can I get the lowest price include the others values from the array

Time:08-01

I have an array like this:

$flight = array (
    array (
        "home" => "AMS",
        "away" => "LHR",    
        "price" => "270"
    ),
    array (
        "home" => "AMS",
        "away" => "LGW",    
        "price" => "216"
    ),   
    array (
        "home" => "EIN",
        "away" => "LHR",    
        "price" => "427"
    ) 
);

I want the values from the cheapest flight. The result should be: AMS LGW 216.

When I loop trough the array I can get the lowest price result but not the other values from the array home and away.

foreach ($flight as $value) { 
    echo $value["home"].' '.$value["away"].' '.$value["price"].'<br>';
    
    $lowest = array_column($flight, "price");
    $min = min($lowest);
}

echo $min;

The result now is only 216 But the result I want AMS LGW 216

How can I create this?

CodePudding user response:

Store the entire item not just the price.

$min = ["price" => 1e10];
foreach ($flight as $value) {
    echo $value["home"] . ' ' . $value["away"] . ' ' . $value["price"] . '<br>';

    if ($value['price'] < $min['price']) {
        $min = $value;
    }
}
print_r($min);

CodePudding user response:

One option is to remember what the values were at the lowest price and just iterate over all of them:

$min = null;

foreach ($flight as $value) { 
    
    if ($min === null || $value['price'] < $min) {
        $minValue = $value;
        $min = $value['price'];
    }
}

echo $minValue["home"].' '.$minValue["away"].' '.$minValue["price"];

CodePudding user response:

Sort the array by field (ASC order) and you'll find the lowest element in the head of your array:

usort($flights, fn($a, $b) => $a['price'] <=> $b['price'])

print_r($flights[0]);

CodePudding user response:

You can use array_keys and with your code.

Here is the code:

    $flight = array(
        array(
            "home" => "AMS",
            "away" => "LHR",
            "price" => "270"
        ),
        array(
            "home" => "AMS",
            "away" => "LGW",
            "price" => "216"
        ),
        array(
            "home" => "EIN",
            "away" => "LHR",
            "price" => "427"
        )
    );

    $lowest = array_column($flight, "price");
    $lowset_array = array_keys($lowest, min($lowest));
    print_r($flight[reset($lowset_array)]);

    //OR
    //print_r($flight[$lowset_array[0]]);

And here is the output:

Array
(
    [home] => AMS
    [away] => LGW
    [price] => 216
)
  • Related