1

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/>";
    }
}
2
  • 1
    As a side note, if you set error_reporting(-1); ini_set('display_errors', 'On') you would see a few notices that say "array to string conversion" Commented Jan 23, 2013 at 14:57
  • 1
    If you see Array echoed, it means you're trying to use an array as a string. Commented Jan 23, 2013 at 14:57

4 Answers 4

2

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:

<?php
if (file_exists("menu.txt"))
{
    $lines = file("menu.txt");
    $sortingbyprice = array();

    foreach ($lines as $line)
    {
        $oneline = explode(",", $line);
        $sortingbyprice[$oneline[0]] = $oneline[1];
    }

    // Sort the array, maintaining key associations.
    asort($sortingbyprice, SORT_NUMERIC);

    foreach ($sortingbyprice as $product=>$price)
    {
        echo $product." ".$price."<br />";
    }
}
?>

If you would like to sort in descending order, you can use

    // Sort the array, maintaining key associations.
    arsort($sortingbyprice, SORT_NUMERIC);

In short: asort() for ascending sorts, arsort() for descending sorts.

Sign up to request clarification or add additional context in comments.

4 Comments

Also note that there is no need to count the lines in the array. :-)
in your version how do I change the sorting order from smallest to highest? I tried to use different sorting commands but they just made the names disapear. I think we have not studies it like this yet but this seems to work very well. :)
There seems still be a problem. Sorting works well for 0-9, but when it scomes to 10+ it does not anymore. Got any idea why not?
Absolutely. If you use arsort($sortingbyprice, SORT_NUMERIC) it will compare the values as numbers, otherwhise as string. So, I've updated my answer yet again. :-)
0

There is an error where your putting your data into an array. This is the correct method:

$sortingbyprice[] = array('name'=>$oneline[0],'price'=>$oneline[1]);
//then to 'echo' a value within the array:
echo $sortingbyprice['name'];

to do every record you could do this:

foreach($sortingbyprice as $price){
    echo $price['name'].': £'.$price['price'];
}

2 Comments

That would fix echoing the values, but it won't help him sort it.
@RocketHazmat I didn't see the array_multisort() my bad.
0

If you want to sort the entire array, you need to do that outside of the for loop. You need to use the loop to parse the file into an array, but then you need to sort it (using usort) outside of the loop.

You are just sorting each individual element of the array as you are reading them in. You're not comparing them with the other elements, so your array_multisort doesn't actually do anything.

<?php
if (file_exists("menu.txt")) {
    // Create the array outside the loop
    $sortingbyprice = array();

    $lines = file("menu.txt");
    $howmanylines = count($lines);

    // Note we're using $howmanylines here
    for($i=0; $i < $howmanylines; $i++) {
        // add each row to the array
        $sortingbyprice[] = explode(",", $lines[$i]);
    }

    // Sort the array by its price
    usort($sortingbyprice, function($a, $b){
        return $a[1] - $b[1];
    });

    // echo the array
    for($i=0; $i < $howmanylines; $i++) {
      $row = $sortingbyprice[$i];
      echo $row[0].' '.$row[1].'<br/>';
    }
}

DEMO: http://codepad.viper-7.com/0Qegab

Comments

-1

The way you're doing it right know you're just inserting another array into the array. Unless you're not looking to really add another array into the array you'll have to omit the array surrounding your values.

$sortingbyprice = array(
    $oneline[0],
    $oneline[1]
);

1 Comment

That would fix echoing the values, but it won't help him sort it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.