PHP belirli kriterlere göre nesne dizisi sıralama?

0 Cevap php

Ben böyle bir şey var:

$i = 0;

foreach($tracks['results'] as $track){
    $trackName[$i] = $track['name'];
    $trackPlaycount[$track['name']] = $track['playcount'];
    $trackPercent[$track['name']] = $track['percent'];
    $i++;
}

$this->trackName = $trackName;
$this->trackPlaycount = $trackPlaycount;
$this->trackPercent = $trackPercent;

nasıl playcount bu nesneleri sıralamak? Ben şimdiye kadar anlıyorum ben muhtemelen gerektiğini okudum ne bir sağ,) işlevini karşılaştırmak ve sonra (usort ile iş yapmak? Ama bunu başarmak için nasıl emin değilim ...

teşekkür ederim




edit: ok, so now I've got it like this:

public function firstmethod(){
    // there are some more parameters here of course
    // but they worked before, not important for the problem
    $i = 0;
    foreach($tracks['results'] as $track){
        $trackName[$i] = $track['name'];
        $trackPlaycount[$track['name']] = $track['playcount'];
        $trackPercent[$track['name']] = $track['percent'];
        // this part is new
        $tracksArray[$i] = array(
            'name' => $trackName[$i], 
            'playcount' => $trackPlaycount[$track['name']], 
            'percentage' => $trackPercent[$track['name']]
        );
        $i++;
    }

    usort($tracksArray, array($this, 'sortByCount'));

    $i = 0;
    // this is to put the new sorted array into the old variables? 
    foreach($tracksArray as $temp){
        $trackName[$i] = $temp['name'];
        $trackPlaycount[$trackName[$i]] = $temp['playcount'];
        $trackPercent[$trackName[$i]] = $temp['percentage'];
        $i++;
    }

    $this->trackName = $trackName;
    $this->trackPlaycount = $trackPlaycount;
    $this->trackPercent = $trackPercent;
}


public function sortByCount($a, $b){
    if($a["playcount"] == $b["playcount"]) {
        return 0;
    }
    return ($a["playcount"] < $b["playcount"]) ? -1 : 1;
}   

this now works... teşekkür ederim everyone

0 Cevap