两个php数组 – 使用另一个数组的值排序一个数组
发布时间:2020-12-13 18:22:56 所属栏目:PHP教程 来源:网络整理
导读:我有两个这样的 PHP数组: 包含ID的X记录数组 WordPress帖子(特别是 订购) 一系列Wordpress帖子 这两个数组看起来像这样: Array One(WordPress帖子ID的排序自定义数组) Array ( [0] = 54 [1] = 10 [2] = 4) 数组二(WordPress Post Array) Array ( [0] = std
我有两个这样的
PHP数组:
>包含ID的X记录数组 这两个数组看起来像这样: Array One(WordPress帖子ID的排序自定义数组) Array ( [0] => 54 [1] => 10 [2] => 4 ) 数组二(WordPress Post Array) Array ( [0] => stdClass Object ( [ID] => 4 [post_author] => 1 ) [1] => stdClass Object ( [ID] => 54 [post_author] => 1 ) [2] => stdClass Object ( [ID] => 10 [post_author] => 1 ) ) 我想按照第一个数组中ID的顺序对wordpress帖子的数组进行排序. 我希望这是有道理的,并且在任何帮助之前都要感谢. 汤姆 编辑:服务器正在运行PHP 5.2.14版
这应该很容易使用
usort ,它使用用户定义的比较函数对数组进行排序.结果可能如下所示:
usort($posts,function($a,$b) use ($post_ids) { return array_search($a->ID,$post_ids) - array_search($b->ID,$post_ids); }); 请注意,此解决方案,因为它使用anonymous functions and closures,需要PHP 5.3. 5.3之前(黑暗时代!)的一个简单解决方案是使用快速循环,然后 $ret = array(); $post_ids = array_flip($post_ids); foreach ($posts as $post) { $ret[$post_ids[$post->ID]] = $post; } ksort($ret); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |