PHP, Jquery get multi array, combine a row

arun kumar asked
php jquery arrays laravel
via

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


Answer
via

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)."n";
}

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
Share This
Posted in: