我正在尝试通过以下代码从数据库中获取值
public function get_value($userid)
{
$this->db->select("*");
$this->db->from("users");
$this->db->order_by("id", "desc");
$query = $this->db->get();
$r1 = $query->result();
echo "<pre>";
print_r($r1);
echo "</pre>";
}
我得到以下数组
Array
(
[0] => stdClass Object
(
[id] => 3
[fullname] => user 3
)
[1] => stdClass Object
(
[id] => 4
[fullname] => User 4
)
[2] => stdClass Object
(
[id] => 5
[fullname] => User 5
)
[3] => stdClass Object
(
[id] => 6
[fullname] => User 6
)
)
我希望以一种方式重新排列数组,如果&#34; $ userid&#34;匹配&#34; id&#34;在数组中,该值应该在第一个位置
例如,如果$ userid = 5,那么数组应该类似于以下
Array
(
[0] => stdClass Object
(
[id] => 5
[fullname] => User 5
)
[1] => stdClass Object
(
[id] => 3
[fullname] => user 3
)
[2] => stdClass Object
(
[id] => 4
[fullname] => User 4
)
[3] => stdClass Object
(
[id] => 6
[fullname] => User 6
)
)
任何人都可以告诉你该怎么做
答案 0 :(得分:3)
您可以在&#34;按字段排序&#34;我认为。类似的东西:
user_status
首先按字段排序,然后按id desc排序。您不需要将每个值都放在字段中(id,?,?,?...),您只需要放置您想要的值select * from users order by field(id,5) desc, id desc
https://www.electrictoolbox.com/mysql-order-specific-field-values/
在您的情况下,这应该是:
field(id,5)
答案 1 :(得分:0)
试试这个:
usort($r1, function (stdClass $a, stdClass $b) use ($userid) {
if ($a->id == $userid) {
return -1;
}
if ($b->id == $userid) {
return 1;
}
return 0;
});
供参考,见:
答案 2 :(得分:0)
试试这个,查看 live demo 。
array_merge(
array_filter($array, function($v) use($userid) {return $v->id == $userid;}),
array_filter($array, function($v) use($userid) {return $v->id != $userid;})
)