mayank mayank - 2 years ago 80
PHP Question

Sorting array of Php objects by two fields

I have formed this array of objects using this:

foreach($snapdealProductCollection as $snapdealProduct){

$item = new stdClass();
$item->id = $snapdealProduct->getId();
$item->name = $snapdealProduct->getTitle();
$item->imgsrc = $snapdealProduct->getImageLink();
$item->price = $snapdealProduct->getEffectivePrice();
$item->source = "";
$item->redirectUrl = $snapdealProduct->getLink().$affProgram;
$item->type = $snapedealType[$snapdealProduct->getId()];
$item->simid = $snapdealsimid[$snapdealProduct->getId()];
$item->stype = 2;

array_push($items, $item);

I need to sort firstly by type, then by simid. How should I sort it?
Full code:

$unsortedItems = $this->getSimilarItems($pid);


usort($unsortedItems , array($this, "cmp"));

function cmp($a, $b)
return strcmp($a->type, $b->type) || strcmp($a->simid, $b->simid);

$unSortedItems is the array returned from the foreach block

Answer Source

You can use usort() function for this, and your comparison function should be like this:

function cmp($a, $b){
    if(strcmp($a->type, $b->type) == 0){
        if ($a->simid == $b->simid) {
            return 0;
        return ($a->simid < $b->simid) ? -1 : 1;
    return strcmp($a->type, $b->type);

usort($unsortedItems , array($this, "cmp"));

Here are the relevant references:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download