dsdf64562672 2017-11-06 06:41 采纳率: 0%
浏览 47
已采纳

PHP,Jquery获取多个数组,组合一行

Concept: Adding Floors and Room counts and Room Numbers in a Hotel and saving it in a db

Front end Design:

Please have a look at this image

enter image description here

Backend what i am getting now:

 "floor" => array:3 [▼
    0 => "3"
    1 => "2"
    2 => "1"
  ]
  "room_count" => array:3 [▼
    0 => "3"
    1 => "3"
    2 => "5"
  ]
  "room_number" => array:11 [▼
    0 => "101"
    1 => "102"
    2 => "103"
    3 => "201"
    4 => "202"
    5 => "203"
    6 => "101"
    7 => "102"
    8 => "103"
    9 => "104"
    10 => "105"
  ]

The Question is:

How can i loop through to get:
Floor 3 has the room numbers 101, 102, 103
Floor 2 has the room numbers 201, 202, 203
Floor 1 has the room numbers 101, 102, 103, 104, 105

  • 写回答

1条回答 默认 最新

  • ds122455 2017-11-06 07:06
    关注

    Iterate through each floor, count the number of rooms, and then determine which room numbers are associated with that floor by working through the array of room numbers.

    Given the array structure you're working with, the trick is that you'll need to have a loop like this one that can track the $prev_index by incrementing $prev_index by the room count at each floor.

    <?php
    $array = array(
        'floor' => array(
            0 => '3',
            1 => '2',
            2 => '1',
        ),
        'room_count' => array(
            0 => '3',
            1 => '3',
            2 => '5',
        ),
        'room_number' => array(
            0  => '101',
            1  => '102',
            2  => '103',
            3  => '201',
            4  => '202',
            5  => '203',
            6  => '101',
            7  => '102',
            8  => '103',
            9  => '104',
            10 => '105',
        ),
    );
    for ($prev_index = 0, $i = 0; $i < count($array['floor']); ++$i) {
        $floor        = $array['floor'][$i];
        $room_count   = $array['room_count'][$i];
        $room_numbers = array_slice($array['room_number'], $prev_index, $room_count);
        $prev_index   = $prev_index + $room_count;
    
        echo 'Floor '.$floor.' has '.$room_count.' rooms, with room numbers '.implode(', ', $room_numbers)."
    ";
    }
    

    Floor 3 has 3 rooms, with room numbers 101, 102, 103
    Floor 2 has 3 rooms, with room numbers 201, 202, 203
    Floor 1 has 5 rooms, with room numbers 101, 102, 103, 104, 105
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 模电中二极管,三极管和电容的应用
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像
  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused
  • ¥20 关于web前端如何播放二次加密m3u8视频的问题
  • ¥15 使用百度地图api 位置函数报错?
  • ¥15 metamask如何添加TRON自定义网络