Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to add elements to the 2nd dimension of a multidimensional array without a key in PHP?

I am writing a page that creates Excel reports based on the fields selected. I am using the SimpleXLSXGen class, which requires a 2-level multidimensional array, with each array within the second dimension becoming a row on the Excel sheet. I fetch values using a query and assign the fields to variables.

When I write it like this, all is fine:

while ($row = mysqli_fetch_assoc($query)) {

    $rows[] = [
        $row["field0"], $row["field1"], $row["field2"], $row["field3"], $row["field4"],
        $row["field5"], $row["field6"], $row["field7"], $row["field8"], $row["field9"],
        $row["field10"], $row["field11"], $row["field12"]
    ];
}

but my aim is to populate the array dynamically. When I write something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

while ($row = mysqli_fetch_assoc($query)) {

    for ($i = 1; $i < $field_count; $i++) {
        $rows[][] = $row["field" . $i];
    }
}

I end up with a single row that contains all of the elements. This is probably a stupid syntax thing, but I have spent way too much time on this now and I think there must be a way to iterate through a multidimensional array without a key. How can I accomplish this?

>Solution :

Create a new array and add it to the first one:

while ($row = mysqli_fetch_assoc($query)) {
    $item = [];
    for ($i = 1; $i < $field_count; $i++) {
        $item[] = $row["field" . $i];
    }
    $rows[] = $item;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading