duandun3178 2011-05-03 13:00
浏览 176

PHP根据另一个数组的内容重新排序对象数组

I have an array of objects that is being generated from an SQL query within a custom Joomla! 1.5 component:

$query = 'SELECT * FROM #__orders_hearaboutus ORDER BY id';
$this->_hearaboutus = $this->_getList($query);

This generates something like:

Array
(
    [0] => stdClass Object
        (
            [id] => 3
            [how_heard] => Our Website
        )

    [1] => stdClass Object
        (
            [id] => 4
            [how_heard] => Other Website
        )

    [2] => stdClass Object
        (
            [id] => 5
            [how_heard] => Word of Mouth
        )

    [3] => stdClass Object
        (
            [id] => 6
            [how_heard] => Other
        )

    [4] => stdClass Object
        (
            [id] => 10
            [how_heard] => Internet Search Engine
        )

    [5] => stdClass Object
        (
            [id] => 11
            [how_heard] => Local Newspaper
        )

    [10] => stdClass Object
        (
            [id] => 16
            [how_heard] => Leaflet by Post
        )

    [11] => stdClass Object
        (
            [id] => 18
            [how_heard] => Club or Society Newsletter
        )

)

This is then generating an HTML select 'Where did you hear about us' drop-down option within an order form.

What I'd like to do is to re-order the list by supplying the IDs in the desired (arbitrary) order, assuming that an array is the best way to do this:

$ordering = array(11,3,4,10,16,5,18,6);

I've found ways of reordering arrays in this way or reordering arrays of objects by keys but I can't work out how to achieve the above?

  • 写回答

3条回答 默认 最新

  • dongwuqi4243 2011-05-03 13:05
    关注

    The most straight-forward way is to do it in SQL:

    $query = 'SELECT * FROM ... ORDER BY FIELD(id,11,3,4,10,16,5,18,6)';
    

    http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_field

    Since it's really not good practice to use arbitrary primary keys as sort criterium, you should really add an additional order column for that purpose.

    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程