I am very new to PhP and programming in general, I looked at similar questions and tried most of the offered solutions but couldn't find a way to apply it to my situation.
I made a filter option on a page, I am now trying to have the filtered results come out as Ascending by price. If I am to use a sort function, where should I be using it in the code for it to make sense?
<?php
require "voitures.php"; [my array][1]
if (isset($_GET["prixMin"])) {
$prixMin = $_GET["prixMin"];
$prixMax = $_GET["prixMax"];
$voitures2 = [];
foreach ($voitures as $voiture) {
if ($prixMin <= $voiture['prix'] && $prixMax >= $voiture['prix']) {
$voitures2[] = $voiture;
}
}
}
?>
<form action=" <?= $_SERVER['PHP_SELF'] ?>" method="GET">
<label for="prixMin">Prix minimal : </label>
<input type="text" name="prixMin" value="<?php if(isset($_GET['prixMin'])){ echo $_GET['prixMin']; }?>">
<label for="prixMax">Prix maximal : </label>
<input type="text" name="prixMax" value="<?php if(isset($_GET['prixMax'])){ echo $_GET['prixMax']; }?>">
<input type="submit" value="Rechercher">
</form>
<br>
<div style="grid-template-columns: repeat(4, max-content)">
<div >Marques</div>
<div >Modeles</div>
<div >Annee</div>
<div >Prix</div>
<?php if (isset($_GET['prixMin'])) { ?>
<?php foreach ($voitures2 as $voiture2) : ?>
<div >
<div ><?= $voiture2["marque"] ?></div>
<div ><?= $voiture2["modele"] ?></div>
<div ><?= $voiture2["annee"] ?></div>
<div ><?= $voiture2["prix"] ?></div>
</div>
<?php endforeach ?>
<?php } else { ?>
<?php foreach ($voitures as $voiture) : ?>
<div >
<div ><?= $voiture["marque"] ?></div>
<div ><?= $voiture["modele"] ?></div>
<div ><?= $voiture["annee"] ?></div>
<div ><?= $voiture["prix"] ?></div>
</div>
<?php endforeach ?>
<?php } ?>
</div>
</main>
<footer>
</footer>
</body>
</html>
CodePudding user response:
array_sort_by_column($voitures2,'prix',SORT_DESC)
function array_sort_by_column($array, $column, $direction = SORT_ASC) {
$reference_array = array();
foreach($array as $key => $row) {
$reference_array[$key] = $row[$column];
}
array_multisort($reference_array, $direction, $array);
return $array;
}