Home > Blockchain >  Sort an array of objects PHP
Sort an array of objects PHP

Time:02-28

I have an array like:

$combinations = [

[{"id":1,"price":11900},{"id":2,"price":499},{"id":3,"price":2099}] //1st combination

[{"id":1,"price":11900},{"id":2,"price":499},{"id":4,"price":999}] //2nd combination

[{"id":1,"price":11900},{"id":2,"price":499},{"id":5,"price":899}] //3rd combination

[{"id":1,"price":11900},{"id":2,"price":499},{"id":6,"price":2999}] //4th combination

]

I need to sort the arrays by the aggregate price of each combination, then I need to return only 40% of them with the highest aggregate price.

CodePudding user response:

<?php

$json = json_decode('[
    [{"id":1,"price":11900},{"id":2,"price":499},{"id":3,"price":2099}],
    [{"id":1,"price":11900},{"id":2,"price":499},{"id":4,"price":999}],
    [{"id":1,"price":11900},{"id":2,"price":499},{"id":5,"price":899}],
    [{"id":1,"price":11900},{"id":2,"price":499},{"id":6,"price":2999}]
    ]');

// var_dump($json);

// ($a, $b) for ASC sorting
// ($b, $a) for DESC sorting
usort($json, function ($b, $a) {

    $a_prices = 0;
    foreach($a as $aa)
        $a_prices  = $aa->price;

    $b_prices = 0;
    foreach($b as $bb)
        $b_prices  = $bb->price;

    return $a_prices - $b_prices;
});

// Find where 40% stops
// It is up to you to choose between ceil() and floor()
$breakpoint = ceil(sizeof($json) * 40 / 100);

$sorted_chunk = array_slice($json, 0, $breakpoint);
var_dump($sorted_chunk);
  • Related