Php 将具有自定义值的键置于前面-多维数组
在过去的几个小时里,我一直在试图找到解决这个问题的办法 我有一个多维数组:Php 将具有自定义值的键置于前面-多维数组,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,在过去的几个小时里,我一直在试图找到解决这个问题的办法 我有一个多维数组: Array ( [0] => stdClass Object ( [id] => 128 [itemID] => 27 [attribute] => xxx ) [1] => stdClass Object ( [id] =>
Array
(
[0] => stdClass Object
(
[id] => 128
[itemID] => 27
[attribute] => xxx
)
[1] => stdClass Object
(
[id] => 129
[itemID] => 27
[attribute] => xxx
)
[2] => stdClass Object
(
[id] => 130
[itemID] => 27
[attribute] => xxx
)
[3] => stdClass Object
(
[id] => 131
[itemID] => 27
[attribute] => xxx
)
[4] => stdClass Object
(
[id] => 132
[itemID] => 27
[attribute] => xxx
)
[5] => stdClass Object
(
[id] => 133
[itemID] => 27
[attribute] => yyy
)
[6] => stdClass Object
(
[id] => 134
[itemID] => 27
[attribute] => xxx
)
)
正如你所看到的obj。5的属性键为“yyy”。
我想把这个包含“yyy”属性键的对象放在前面,就像重新排序一样,所以当我foreach时,yyy结果是第一个
我尝试了在网上找到的不同代码片段,但找不到一个对我有帮助的。看到这个-,可能会对你有帮助
所以,对数组进行排序,并使用自定义函数来比较属性是否是您想要的(对于yyy,返回-1作为$a,对于yyy,返回1作为$b,否则返回0)请参见此-,可能会对您有所帮助
因此,对数组进行排序,并使用自定义函数,比较属性是否为所需的属性(对于yyy,返回-1作为$a,对于yyy,返回1作为$b,否则返回0)给定上述数组:
function sortMyArray($item1, $item2) {
$result = 0;
if ($item1->attribute == 'yyy') {
$result = -1;
}
else if ($item2->attribute == 'yyy') {
$result = 1;
}
return $result;
}
usort($yourArray, "sortMyArray");
鉴于上述阵列:
function sortMyArray($item1, $item2) {
$result = 0;
if ($item1->attribute == 'yyy') {
$result = -1;
}
else if ($item2->attribute == 'yyy') {
$result = 1;
}
return $result;
}
usort($yourArray, "sortMyArray");