简体   繁体   中英

filter "the max count" for array in laravel

I have an array in Laravel. I want to show some value of this array on the index page.

my array:

$product = [
    '0' => array(
     'name' => 'product1',
     'count' => '30'
),
    '1' => array(
     'name' => 'product2',
     'count' => '2'
),
    '2' => array(
     'name' => 'product3',
     'count' => '5'
),
    '3' => array(
     'name' => 'product4',
     'count' => '33'
),
    '4' => array(
     'name' => 'product5',
     'count' => '30'
),
    '5' => array(
     'name' => 'product6',
     'count' => '29'
)]; 

I want to show from the highest quantity to the lowest value and limit this to 4 counts.

like this

<h2>product4</h2>
<p>33</p>
<hr>

<h2>product1</h2>
<p>30</p>
<hr>

<h2>product5</h2>
<p>30</p>
<hr>

<h2>product6</h2>
<p>29</p>
<hr>

尝试这个

 $sortedarray = collect($product)->sortBy('count')->reverse()->take(4)->toArray();

try to use array_multisort ( documentation )

array_multisort(array_column($product, 'count'), SORT_DESC, $product);
echo '<pre>';
print_r($product);
exit;

Check example

Sorted array push into foreach loop:

public function getSortedProducts(){

    $product = [
        '0' => array(
         'name' => 'product1',
         'count' => '30'
    ),
        '1' => array(
         'name' => 'product2',
         'count' => '2'
    ),
        '2' => array(
         'name' => 'product3',
         'count' => '5'
    ),
        '3' => array(
         'name' => 'product4',
         'count' => '33'
    ),
        '4' => array(
         'name' => 'product5',
         'count' => '30'
    ),
        '5' => array(
         'name' => 'product6',
         'count' => '29'
    )]; 

    array_multisort(array_column($product, 'count'), SORT_DESC, $product);

    return view('your_blade_name',compact('product'));
}

Blade:

@foreach($product as $row)
        @if($loop->iteration > 5) // or other logic
            @break
        @endif
    <h3>{{ $row['name'] }}</h3>
    <p>{{ $row['count'] }}</p>
    <hr> 
@endforeach

Use usort function

function sortByCount($a, $b) {
   return $b['count'] - $a['count'];
}
usort($product,'sortByCount');
print_r($product);

foreach($product as $k => $val){
   if($k <= 3){
      echo "Your HTML";
      echo '<br/>';
   }

}

You can try this code:

$sorted = collect($product)->sortByDesc('count')->toArray();  // for sort array
$output = array_slice($sorted, 0, 4);  // for return first four indexs 

使用array_multisort

array_multisort(array_column($product, 'count'), SORT_DESC, $product);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM