Solved. Thanks for everyone who helped with it by answers or comments and especially for those who spent couple of minutes typing some written explanations with their code so I actually got what is happening 🙂
Just some newbie php question. I have troubles in solving how to make this working. Basically I just want to sort menu by price, which includes only the name and the price.
Menu.txt looks like this:
Meat,1
Salad,3
Juice,2
But after running the program it echoes:
Array Array
Array Array
Array Array
And I would like to have it printed like:
Meat,1
Juice,2
Salad,3
Which makes me think I cant use variables in array() just like that so I wonder how I should actually do it? Code is down below and everything else works well in my program except sorting by price (if I just print .txt file without trying to sort is goes fine etc..)
<?php
if (file_exists("menu.txt"))
{
$lines = file("menu.txt");
$howmanylines = count($lines);
for($i=0; $i < $lines; $i++) {
$oneline = explode(",",$lines[$i]);
$name = $oneline[0];
$price = $oneline[1];
$sortingbyprice = array(
array($name),
array($price)
);
array_multisort($sortingbyprice[0], $sortingbyprice[1], SORT_NUMERIC, SORT_ASC);
echo $sortingbyprice[0] . " ";
echo $sortingbyprice[1] . "<br/>";
}
}
You’re inputting arrays into an array and sorting everytime you input a new value into the array.
This code doesn’t: first it iterates through the file, adding the menu items to an associative array using the following format:
$sortingbyprice[product] = price. Then it sorts the array and loops through the sorted array, generating an output (which, of course, can be altered to suit your needs).To sort in ascending order:
If you would like to sort in descending order, you can use
In short: asort() for ascending sorts, arsort() for descending sorts.