perun
perun

Reputation: 23

how to sort items in array by one specific value

i have an array with an items and every item have few values. I need to sort items in the array by value 'level' and than i need to echo some piece of code for every item.

Database looks something like this.

$database= [
[
'name'=> 'item_one',
'preview_href'=> 'item_one.php',
'img_src'=> 'pictures/item_one.jpg',
'level'=> 5.9,
'description'=> 'This product is.....' ,
],
[
'name'=> 'item_two',
'preview_href'=> 'item_two.php';
'img_src'=> 'pictures/item_two.jpg',
'level'=> 7.5,
'description'=> 'This product is.....' ,
  ],
 ];

I have tried something like this but it didnt work.

function top_items($two)
{
  $two= arsort($two);

     foreach (array_slice($two, 0, 20) as $one)
    {
        echo '<div class="item">
        <a href="'. $one['preview_href'].'">
       <img src="' . $one['img_src'] .'">
       <p> '.$one['name'].' (' . $one['release']. ') </p>
          </a>
       </div>';
     }

   };

my expected output: I need to use this code for first 20 or whatever number of items with biggest ['level'] value:

        echo '<div class="item">
        <a href="'. $one['preview_href'].'">
        <img src="' . $one['img_src'] .'">
        <p> '.$one['name'].' (' . $one['release']. ') </p>
       </a>
       </div>';

$one is an one item(array) in a big array database. In big database i have all of the items.

Upvotes: 0

Views: 42

Answers (1)

Phuc Lam
Phuc Lam

Reputation: 370

You can use like this to sort subarray by value:

In <= PHP 5.6:

usort($database, function ($a, $b) {
    return $a['level'] - $b['level'];
});

In >= PHP 7.0:

usort($database, function ($a, $b) {
    return $a['level'] <=> $b['level'];
});

Then get first 20 items (can replace 20 by x number):

$output = array_slice($database, 0, 20);

Upvotes: 1

Related Questions