gpt4 book ai didi

php - 替代值应存储在 php 数组中的替代位置

转载 作者:行者123 更新时间:2023-11-28 23:24:17 25 4
gpt4 key购买 nike

当从 mysql 中获取值时,这些值将按顺序存储在数组中。但我希望这些值存储在数组中的替代位置。这里有一些来自表的个别值


course_id('1') 值

Array ( 
[0] => 15BCA01 [1] => 15BCA02 [2] => 15BCA03 [3] => 15BCA04 [4] => 15BCA05
[5] => 15BCA06 [6] => 15BCA07 [7] => 15BCA08 [8] => 15BCA09 [9] => 15BCA10
[10] => 15BCA11
)

course_id('2') 值:

Array ( 
[0] => 15MCA01 [1] => 15MCA02 [2] => 15MCA03 [3] => 15MCA04 [4] => 15MCA05
)

course_id('3') 值:

 Array ( 
[0] => 15MBA01 [1] => 15MBA02 [2] => 15MBA03 [3] => 15MBA04 [4] => 15MBA05
)

course_id('4') 值:

Array ( 
[0] => 15MSC01 [1] => 15MSC02 [2] => 15MSC03
)

course_id('5') 值:

Array ( 
[0] => 15TAM01 [1] => 15TAM02
)

当我执行mysql命令时

 select  register_number from master where master_course_id in('1','2','3','4','5');

我得到的当前输出(与系列中的往常一样):

Array ( 
[0] => 15BCA01 [1] => 15BCA02 [2] => 15BCA03 [3] => 15BCA04 [4] => 15BCA05
[5] => 15BCA06 [6] => 15BCA07 [7] => 15BCA08 [8] => 15BCA09 [9] => 15BCA10
[10] => 15BCA11 [11] => 15MCA01 [12] => 15MCA02 [13] => 15MCA03 [14] => 15MCA04
[15] => 15MCA05 [16] => 15MBA01 [17] => 15MBA02 [18] => 15MBA03 [19] => 15MBA04
[20] => 15MBA05 [21] => 15MSC01 [22] => 15MSC02 [23] => 15MSC03 [24] => 15TAM01
[25] => 15TAM02
)

我想要的期望输出(替代位置):

Array ( 
[0] => 15BCA01 [1] => 15MCA01 [2] => 15BCA02 [3] => 15MCA02 [4] => 15BCA03
[5] => 15MCA03 [6] => 15BCA04 [7] => 15MCA04 [8] => 15BCA05 [9] => 15MCA05
[10] => 15BCA06 [11] => 15MBA01 [12] => 15BCA07 [13] => 15MBA02 [14] => 15BCA08
[15] => 15MBA03 [16] => 15BCA09 [17] => 15MBA04 [18] => 15BCA10 [19] => 15MBA05
[20] => 15BCA11 [21] => 15MSC01 [22] => 15TAM01 [23] => 15MSC02 [24] => 15TAM02
[25] => 15MSC03
)

如果数组中的第一个值来自 course_id ('1') 意味着第二个值应该来自 course_id ('2') 或者他们应该添加到数组中.如果course_id ('1') 完成 下一个 course_id('3') 应该开始添加当前的course_id (' 2') 。同样,所有 course_id 值都应该交替添加到数组中。如何在 php 中实现这一点

最佳答案

在 MySQL 中,您需要使用用户定义的变量在 master_course_id 组内添加排序。

SELECT register_number
FROM (
SELECT master_course_id, register_number,
@position := IF(master_course_id = @prev_course, @position+1, 1) AS position,
@prev_course := master_course_id
FROM (SELECT * FROM master
WHERE master_course_id IN ('1', '2', '3', '4', '5')
ORDER BY master_course_id, register_number) AS m,
CROSS JOIN (SELECT @position := 0, @prev_course := null) AS vars
) AS t
ORDER BY position, master_course_id

子查询添加了一个额外的 position 列,该列在每个类(class) ID 中按顺序递增。然后外部查询首先按位置重新排序所有内容,然后按类(class) ID。

关于php - 替代值应存储在 php 数组中的替代位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40020064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com