问题描述
我在PHP两个数组。第一阵列($ author_array)被以特定的顺序包含user_ids的,像这样:(8,1,6)
I have two arrays in PHP. The first array ($author_array) is comprised of user_ids in a particular order, like so: (8, 1, 6)
第二个数组($ user_results)由对象的这样一个数组的:
The second array ($user_results) is comprised of an array of objects like so:
Array
(
[0] => stdClass Object
(
[ID] => 1
[user_login] => user1
)
[1] => stdClass Object
(
[ID] => 6
[user_login] => user6
)
[2] => stdClass Object
(
[ID] => 8
[user_login] => user8
)
)
我想之类的第二个数组所以它是按照这个顺序,其数值顺序相匹配的第一个阵列中的(8,1,6)。所以它会是这样的:
I'd like to "sort" the second array so it's in this order, which matches the order of the values in the first array of (8, 1, 6). So it'd look like this:
Array
(
[0] => stdClass Object
(
[ID] => 8
[user_login] => user8
)
[1] => stdClass Object
(
[ID] => 1
[user_login] => user1
)
[2] => stdClass Object
(
[ID] => 6
[user_login] => user6
)
)
我对数据结构薄弱。我怎么能这样做呢? : - )
I'm weak on data structures. How could I do this? :-)
在此先感谢您的帮助!
鲍勃
推荐答案
使用并提供使用位置自定义比较函数在您的订购数组的关键在于确定排序顺序,例如:是这样的:
Use usort and provide a custom comparison function which uses the position of the key in your "ordering" array to determine the sort order, e.g. something like:
function cmp($a, $b)
{
global $author_array;
$pos1=array_search ($a->ID, $author_array);
$pos2=array_search ($b->ID, $author_array);
if ($pos1==$pos2)
return 0;
else
return ($pos1 < $pos2 ? -1 : 1);
}
usort($user_results, "cmp");
这篇关于排序在PHP对象数组按特定的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!