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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序