mayank mayank - 7 months ago 18
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->vendortype=2;
$item->name = $snapdealProduct->getTitle();
$item->imgsrc = $snapdealProduct->getImageLink();
$item->price = $snapdealProduct->getEffectivePrice();
$item->source = "Snapdeal.com";
$item->redirectUrl = $snapdealProduct->getLink().$affProgram;
$item->type = $snapedealType[$snapdealProduct->getId()];
$item->simid = $snapdealsimid[$snapdealProduct->getId()];
$item->stype = 2;
$i++;

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);

$vendors=$this->getAllVendors();


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

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: