看this post看起来很简单,但我无法做到这一点。
我构建了一个像这样的对象数组:
objs = array();
loop..
$obj = array(
"prop1" => 'cccc a a a a 32423f sdf',
"prop2" => 'sdlkfjsldkfj',
"prop3" => 'slkfjs93s3jfsl'
);
$Objs[] = $obj2;
然后我尝试按字母顺序对属性进行排序:
function cmp($a, $b) {
return strcasecmp($a->prop1, $b->prop1);
}
usort($fileObjs, "cmp");
但它没有按字母顺序排序,不确定我哪里出错了。这是一个完整的例子:
$objs = array();
$obj1 = array(
"prop1" => 'aaaa a a a a 32423f sdf',
"prop2" => 'sdlkfjsldkfj',
"prop3" => 'slkfjs93s3jfsl'
);
$obj2 = array(
"prop1" => 'bbb a a a a 32423f sdf',
"prop2" => 'sdlkfjsldkfj',
"prop3" => 'slkfjs93s3jfsl'
);
$obj3 = array(
"prop1" => 'cccc a a a a 32423f sdf',
"prop2" => 'sdlkfjsldkfj',
"prop3" => 'slkfjs93s3jfsl'
);
$objs[] = $obj2;
$objs[] = $obj1;
$objs[] = $obj3;
function cmp($a, $b) {
return strcasecmp($a->prop1, $b->prop1);
}
usort($objs, "cmp");
var_dump($objs);
结果输出:
array(3) {
[0]=>
array(3) {
["prop1"]=>
string(23) "cccc a a a a 32423f sdf"
["prop2"]=>
string(12) "sdlkfjsldkfj"
["prop3"]=>
string(14) "slkfjs93s3jfsl"
}
[1]=>
array(3) {
["prop1"]=>
string(23) "aaaa a a a a 32423f sdf"
["prop2"]=>
string(12) "sdlkfjsldkfj"
["prop3"]=>
string(14) "slkfjs93s3jfsl"
}
[2]=>
array(3) {
["prop1"]=>
string(22) "bbb a a a a 32423f sdf"
["prop2"]=>
string(12) "sdlkfjsldkfj"
["prop3"]=>
string(14) "slkfjs93s3jfsl"
}
}
答案 0 :(得分:3)
这似乎是令人困惑的对象和数组对象。您的cmp函数正在比较数组对象中不存在的属性。
如果你:
echo "comparing {$a->prop1} vs {$b->prop1}";
在cmp方法中,您会注意到prop1是空的。
您可以通过引用像
这样的数组索引来修复代码function cmp($a, $b) {
return strcasecmp($a['prop1'], $b['prop1']);
}