我有一个从自定义Joomla中的SQL查询生成的对象数组! 1.5分量:
$query = 'SELECT * FROM #__orders_hearaboutus ORDER BY id';
$this->_hearaboutus = $this->_getList($query);
这会生成如下内容:
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
)
)
然后在订单表单中生成一个HTML选择“你在哪里听说过我们”下拉选项。
我想做的是通过以所需(任意)顺序提供ID来重新排序列表,假设数组是执行此操作的最佳方式:
$ordering = array(11,3,4,10,16,5,18,6);
我已经找到了以这种方式重新排序数组或通过键重新排序对象数组的方法,但我无法弄清楚如何实现上述目标?
答案 0 :(得分:1)
最直接的方法是在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
由于将任意主键用作排序标准并不是一种好的做法,因此您应该为此添加额外的order
列。
答案 1 :(得分:0)
您可以在MySQL中使用array_multisort()
提及@deceze或在PHP中执行此操作:
array_multisort($this->_hearaboutus, $ordering, SORT_ASC);
答案 2 :(得分:0)
@deceze提到的通过MySQL做这件事可能是最好的方法,但这是实现你所需要的快捷方式。
class testObj {
public $id;
function __construct($id) {
$this->id = $id;
}
}
$order = array( 11, 3, 4, 10, 16, 5, 18, 6);
$objects = array(
new testObj(3),
new testObj(4),
new testObj(5),
new testObj(6),
new testObj(10),
new testObj(11),
new testObj(16),
new testObj(18)
);
$neworder = array();
foreach ( $order as $ord ) {
foreach ( $objects as $obj ) {
if ( $obj->id == $ord ) {
$neworder[] = $ord;
}
}
}
print_r( $neworder );