douqian1975 2012-08-18 15:17
浏览 23
已采纳

如何创建每个第n项的数组?

Say I have the following table:

name
----
A
B
C
D
E
F
G
H
I

I can extract this from MySQL and put it in an array:

$result = mysql_query("SELECT * FROM names ORDER BY name DESC");
while ($row = mysql_fetch_object($result)) {
  $names[] = $row->name
}

What I am now looking for is a script that loops through $names and returns pairs, for instance every 3rd name:

array(
  [A] => [C],
  [B] => [D],
  [C] => [E],
  [D] => [F]
  [E] => [G]
  [F] => [H]
  [G] => [I]
)

Or, for instance, every 4th name:

array(
  [A] => [D],
  [B] => [E],
  [C] => [F],
  [D] => [G]
  [E] => [H]
  [F] => [I]
)

The number of names in between (3 in the fist example, 4 in the second) should be variable. Does anybody know how to do this in php?

  • 写回答

3条回答 默认 最新

  • douxian9010 2012-08-18 15:22
    关注

    You can do this using a fairly simple for loop.

    Here's an example. All you need to do is tweak $seperation:

    <?php
    
    $array = array('A','B','C','D','E','F','G','H','I');
    $seperation = 3;
    $assoc = array(); // stores result
    
    for($i = 0; $i+$seperation < count($array); $i++) {
       $assoc[$array[$i]] = $array[$i + $seperation];
    }
    
    print_r($assoc);
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)