Php 如何将目标对象移动到索引对象数组的前面?
我有一个索引对象数组,如下所示:Php 如何将目标对象移动到索引对象数组的前面?,php,arrays,sorting,object,multidimensional-array,Php,Arrays,Sorting,Object,Multidimensional Array,我有一个索引对象数组,如下所示: Array ( [0] => St Object ( [pId] => 6590153 [prId] => 5371 [expirationDate] => 2018-07-10 23:59:59 [creationDate] => 2018-01-10 11:58:29
Array
(
[0] => St Object
(
[pId] => 6590153
[prId] => 5371
[expirationDate] => 2018-07-10 23:59:59
[creationDate] => 2018-01-10 11:58:29
[pkid] => 12345
[parentObj] => s Object
(
[id] => 654250
[userID] => 776134
[pkid] ] => 12345
)
[ur] => 5899
[overAgeRate] => 1.00
)
[1] => St Object
(
[pId] => 6590154
[prId] => 5371
[expirationDate] => 2018-07-10 23:59:59
[creationDate] => 2018-01-10 11:58:29
[pkid] => 12346
[parentObj] => s Object
(
[id] => 654250
[userID] => 776134
[pkid] ] => 12346
)
[ur] => 58
[overAgeRate] => 1.00
)
)
我想根据我的指针值重新排列数组。例如,$needle=12346
基于此值,第二个对象需要成为第一个元素。结果数组将是:
Array
(
[0] => St Object
(
[pId] => 6590154
[prId] => 5371
[expirationDate] => 2018-07-10 23:59:59
[creationDate] => 2018-01-10 11:58:29
[pkid] => 12346
[parentObj] => s Object
(
[id] => 654250
[userID] => 776134
[pkid] ] => 12346
)
[ur] => 58
[overAgeRate] => 1.00
)
[1] => St Object
(
[pId] => 6590153
[prId] => 5371
[expirationDate] => 2018-07-10 23:59:59
[creationDate] => 2018-01-10 11:58:29
[pkid] => 12345
[parentObj] => s Object
(
[id] => 654250
[userID] => 776134
[pkid] ] => 12345
)
[ur] => 5899
[overAgeRate] => 1.00
)
)
如何以简单的方式执行此操作?这些方法会将目标对象移动到数组的前面(如果存在),如果找不到目标,则不会移动任何内容 方法#1() 方法#2:()
我已经使用了下面的代码,它工作得很好$pkid='12346';foreach($arr as$k=>$v){$pkId=$v->pkId;if($pkId==$pkId){unset($arr[$k]);array_unshift($arr,$v);break;}交换
数组拼接()
forunset()
当然是一个更好的选择。我已经更新了我的答案。我不建议使用区分大小写来区分相似的变量——这会使代码更难阅读。我还有另一个原则,即不应声明一次性使用的变量——我在更新的答案中没有声明$pkId
这是原因。
$pkid='12346';
usort($array,function($a,$b)use($pkid){ // put needle into function scope
if($a->pkid!=$pkid && $b->pkid!=$pkid){ // neither object matches needle
return 0; // no move
}
return $a->pkid==$pkid ? -1 : 1; // $a or $b matches; appropriately move
});
var_export($array);
$pkid='12346';
foreach($array as $k=>$v){
if($v->pkid== $pkid){ // found the needle
unset($array[$k]); // remove object from array
array_unshift($array,$v); // reinsert it at the front (reindex keys)
break; // no reason to continue iterating
}
}
var_export($array);