PHP在关联数组中按位置对数组排序
例如,我想对引用属性在另一个数组中的位置的数组进行排序PHP在关联数组中按位置对数组排序,php,arrays,sorting,ksort,Php,Arrays,Sorting,Ksort,例如,我想对引用属性在另一个数组中的位置的数组进行排序 $referenceArray = ['red', 'green', 'blue']; $testArray = [obj1, obj2, obj3, obj4]; foreach($testArray as $object) { if($object->colour === "red") { // push to TOP of array } elseif($object-color == "gre
$referenceArray = ['red', 'green', 'blue'];
$testArray = [obj1, obj2, obj3, obj4];
foreach($testArray as $object) {
if($object->colour === "red") {
// push to TOP of array
} elseif($object-color == "green") {
// push to MIDDLE of array
} elseif($object->color === "blue") {
// push to BOTTOM o array
}
}
这是否可以使用内置的php排序方法实现?或者只能像我上面的伪代码那样完成
由于数组中有对象,因此除了
usort
之外,您不能真正使用任何内置方法,除非您愿意将对象强制转换为数组:
$referenceArray = ['red', 'green', 'blue'];
$testArray = [obj1, obj2, obj3, obj4];
usort($testArray, function ($x, $y) use ($referenceArray) {
$xIndex = array_search($x->color, $referenceArray); //Is it color or colour?
$yIndex = array_search($y->color, $referenceArray);
return $xIndex <=> $yIndex;
});
$referenceArray=[“红色”、“绿色”、“蓝色”];
$testArray=[obj1、obj2、obj3、obj4];
usort($testArray,function($x,$y)use($referenceArray){
$xIndex=array\u search($x->color,$referenceArray);//是颜色还是颜色?
$yIndex=array\u search($y->color,$referenceArray);
返回$xIndex$yIndex;
});
其思想是:在比较对象$x和对象$y时,从$referenceArray
获取$x
和$y
的颜色索引,并返回这些索引的比较结果 请参见中的“分类为手动静态顺序”下的“基本回答”。在这里应用它有什么特别的问题吗?