开发者

Appending Elements to a existing array within an array (2d array) - PHP

开发者 https://www.devze.com 2023-02-28 05:23 出处:网络
I am still new to PHP. My problem: Warning: array_push() expects parameter 1 to be array Description: I have a list of room numbers that I am parsing. The first number of the room number refers to t

I am still new to PHP.

My problem: Warning: array_push() expects parameter 1 to be array

Description: I have a list of room numbers that I am parsing. The first number of the room number refers to the floor of the room开发者_JS百科. I want to create a 2d array that holds floor numbers, and each floor consists of the rooms.

Code:

    $array = self::getAllRooms();
    $floorArray = array();
    foreach($array as $row)
    {
        $floorNum = substr($row['room_no'],0,1);
        if (in_array($floorNum, $floorArray))
        {
            array_push($floorArray[$floorNum], $row['room_no']);
        }
        else 
        {
            array_push($floorArray, $floorNum);
            array_push($floorArray[$floorNum], $row['room_no']);
        }
    }

How do I append the room numbers to the "1" category referring to floor 1?

Thanks a lot!


Code:

$array = array(array('Stack','Overflow'));

$array[0][] = '.com';
// or
array_push($array[0],'.com');

Output:

Array
(
    [0] => Array
        (
            [0] => Stack
            [1] => Overflow
            [2] => .com
            [3] => .com
        )

)


You have a bug here:

array_push($floorArray, $floorNum);
array_push($floorArray[$floorNum], $row['room_no']);

The first line pushes an element with a value of $floorNum into the array, but the second line expects an element with a key equal to $floorNum to be present.

You can do what you want much simpler:

foreach($array as $row)
{
    $floorNum = substr($row['room_no'],0,1);
    $floorArray[$floorNum][] = $row['room_no'];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消