Question

I'm building a web-app that has a rather large (10K rows) reference table.

Table reference has a category, id , description.

As I'm using this reference a data a lot to fill drop-down boxes and such, I'm trying to put them in arrays. I had them in one large array it first, but it seems to me it's more efficient to have an array per category within the reference table.

The dynamic variable names are created, but populating them from another array is not working.

$r_refcats = mysqli_query($global_dbh,"select distinct(cat) from reference");
while(($row = mysqli_fetch_array($r_refcats)) != false){ $$row[0]=array();};

$r_references = mysqli_query($global_dbh,"select cat,id,description from reference");
while(($row = mysqli_fetch_array($r_references)) != false) { $$row[0]=array($row);}

Because I can't use a $$row[0][] in the last line, it keeps overwriting the same value :)

Any tips on how to do this correctly?

Was it helpful?

Solution

You need to add to the array, not just rewrite it:

$r_refcats = mysqli_query($global_dbh,"select distinct(cat) from reference");
while(($row = mysqli_fetch_array($r_refcats)) != false) {
    ${$row[0]}=array();
}

$r_references = mysqli_query($global_dbh,"select cat,id,description from reference");
while(($row = mysqli_fetch_array($r_references)) != false) {
    ${$row[0]}[] = $row;
}

Also, I think you just want to use $row as your array, not an array of $row. In other words, I think you want to have the data be the data in $row, not array(0=>$row) -- hence my edit to the last line.

OTHER TIPS

How about array_push(), it should treat it the same as []:

while(($row = mysqli_fetch_array($r_references)) != false) {
    //$$row[0]=array($row)
    array_push($$row[0],array($row));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top