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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?