1

I receive data by JSON and I can read the data and show it by the icons in one big list how they were received. What I want to do is sort the objects by price and display them as icons in two columns on a page.

In one column the free items (price = 0) and in the other column the paid items (price > 0)

I assume I have to use usort (which I don't really understand), but I have no idea, how it would be placed into my existing code and how I could create the divs to show the icons in two columns left and right.

This is my simplified code right now:

$arr = json_decode($jsondata,true);

    if ($arr['resultCount'] > '0') {

    foreach($arr['results'] as $item) {
        $icon = $item['artwork'];
        $title = $item['trackName'];
        $price = $item['price'];

        if ($price == 0 ) {

        echo '<div class="iconsearch" style="background-image: url('.$icon.');"><a href="'.$title.'">'.$title.'<img src="images/iconmask.png"/></a></div>';
        } else {
        echo '<div class="iconsearch" style="background-image: url('.$icon.');"><a href="'.$title.'">'.$title.'<img src="images/iconmask.png"/></a></div>';
        }
    }
}
1

1 Answer 1

2

you need to sort the results coming in. For this you should use usort and provide your own functionality:

usort — Sort an array by values using a user-defined comparison function

try the following:

if ($arr['resultCount'] > 0) {

    usort($arr['results'], function ($a, $b) {
        return $a["price"] > $b["price"];
    });

    var_dump($arr['results']);

    //.. now that its sorted, you can iterate and do as you wish

}

source: http://php.net/manual/en/function.usort.php

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

5 Comments

YAY! Thanks! It sorts the data by price now. Now I have to find out, how to put them in two different divs :-)
Nice. Glad I could help. Let me know if you get stuck again.
Ok, I tried what I could with my php knowledge, but I am unable to put them by price into two different tables (div). Can you help me with that too?
sure no problem. Can you post another question and send me that link?
I solved the problem differently and it works fine. Thank you for your offer though!

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.