Home > OS >  How to arrange an array in PHP
How to arrange an array in PHP

Time:03-02

I have two rooms and each room has three blocks, Please see my form and array structure below.

Html Form https://i.stack.imgur.com/3kDPr.png

Got this array after submitting the form

Rooms Array

Array(
 [0] => 8
 [1] => 9
)

And Blocks Array

Array (
 [0] => A,B,C
 [1] => X,Y,Z
)

I want to

$array = ('room' => 8,'block' => A),
     ('room' => 8,'block' => B),
     ('room' => 8,'block' => C),
     ('room' => 9,'block' => X),
     ('room' => 9,'block' => Y)
     ('room' => 9,'block' => Z);

Please help me to fix this issue

CodePudding user response:

$rooms = [8,9];
$blocks = [['A','B','C'],['X','Y','Z']];
$array = [];
foreach($rooms as $key => $room)
    foreach($blocks as $k => $block)
        if($key == $k)
            foreach($block as $b)
                $array[] = ['room' => $room,'block'=>$b];
                
print_r($array);

Output:

Array
(
    [0] => Array
        (
            [room] => 8
            [block] => A
        )

    [1] => Array
        (
            [room] => 8
            [block] => B
        )

    [2] => Array
        (
            [room] => 8
            [block] => C
        )

    [3] => Array
        (
            [room] => 9
            [block] => X
        )

    [4] => Array
        (
            [room] => 9
            [block] => Y
        )

    [5] => Array
        (
            [room] => 9
            [block] => Z
        )

)

CodePudding user response:

Thank you all it will work for me.

    $room_type_id = (array) $request->input("room_type"); //multiple value
    $block_name = (array) $request->input("block_name"); //multiple value

    $array = [];
    foreach($room_type_id as $key => $room)
        foreach($block_name as $k => $block)
            if($key == $k)
                foreach(explode(',', $block) as $b)
                    $array[] = ['room' => $room,'block'=>$b];
    
    echo '<pre>';
    print_r($array);

Array(
[0] => Array
    (
        [room] => 8
        [block] => A
    )

[1] => Array
    (
        [room] => 8
        [block] => B
    )

[2] => Array
    (
        [room] => 8
        [block] => C
    )

[3] => Array
    (
        [room] => 9
        [block] => X
    )

[4] => Array
    (
        [room] => 9
        [block] => Y
    )

[5] => Array
    (
        [room] => 9
        [block] => Z
    )

)

  • Related