按值对按键对象数组进行排序

时间:2015-12-05 20:11:13

标签: php sorting

我一直在尝试使用usort()中包含的对象实例变量值对键控数组进行排序,它似乎不是正确使用的工具。希望有人对排序对象有一些建议,如下所示。

提前致谢!

$ary = array("apple" => object DatePrice ("date" => "2015-12-01", "price" => 3), 
               "orange" => object DatePrice ("date" => "2015-12-02", "price" => 4), 
               "banana" => object DatePrice ("date" => "2015-12-01", "price" => 0.50),
               "pear" => object DatePrice("date" => "2015-12-01", "price" => 1),
                );

期望的结果:

$ary = array("orange" =>object DatePrice("date" => "2015-12-02", "price" => 4),
              "apple" => object DatePrice("date" => "2015-12-01", "price" => 3), 
               "pear" => object DatePrice("date" => "2015-12-01", "price" => 1),
                "banana" => object DatePrice("date" => "2015-12-01", "price" => 0.50));

发现这篇文章:Sort array of objects by object fields

但我需要对键控数组进行排序..

2 个答案:

答案 0 :(得分:2)

像这样......

#include <string>
#include <iostream>
using namespace std;
#ifndef SCHOOL_H
#define SCHOOL_H
class School {
public:
string name;      
string state;    
int women;      
int rateAI;     
int rateSys;      
int rateTheory;  
int effectiveness;  
int ratePubs;     
int overallRating;  // overall rating that considers all of the above factors 
School ();
School (string myName, string myState, int theWomen, int myRateAI, int myRateSys,
    int myRateTheory, int myEffectiveness, int myRatePubs);
void printSchoolInfo ();
void computeRating (int weightWomen, int weightAI, int weightSys, 
            int weightTheory, int weightEffect, int    weightPubs);
};

bool operator ==(const School &x,const School &y);
bool operator >(const School &x,const School &y);
bool operator <(const School &x,const School &y);
bool operator >=(const School &x,const School &y);
bool operator <=(const School &x,const School &y);
bool operator !=(const School &x,const School &y);
#endif

对于对象,它不会改变很多,它只是一个功能,在这里检查你需要的任何东西......

uasort($ary, function ($a, $b) {
    return floatval($b['price']) - floatval($a['price']);
});

答案 1 :(得分:0)

看看array_multisort()。使用该方法,您可以根据其键对(多维)数组进行排序,并指定其排序顺序。