Double Dollar Sign - Assign Array key=>value

2.2k views Asked by At

I would like to create 3 different arrays which can change depending on which fields are pulled from some mysql tables.

This is the code I have:

    // Gather db rows with query
    $compQuery['subCats'] = mysql_query("SELECT id,name,category FROM subcategories ORDER BY id DESC");
    $compQuery['cats'] =    mysql_query("SELECT id,name FROM categories ORDER BY id DESC");
    $compQuery['mans'] =    mysql_query("SELECT id,name,link FROM manufacturers ORDER BY id DESC");

    // Place rows into arrays
    foreach($compQuery as $name=>$query){

        $name = array();

        while($data = mysql_fetch_array($compQuery[$name])){
            foreach($data as $key=>$value){

                $$name[$key] = $value;                  

            }

        }

    }

What I would expect this to produce is 3 arrays: subCats, cats and mans each with the value pairs. Instead of finding the $$name variable and assigning [$key] = $value to the array it is taking a single letter out of the $$name variable and assigning the $value to this new variable.

For example, if $name = 'subCats', $key = '3', and value = 'machine tools'

It would create the variable $C using the 3rd letter in subCats:

$C = 'machine tools' 

What it should do is create:

$subCats[3] = 'machine tools';

Now, obviously there are easier ways to create separate arrays for each query, and I have modified my code to a lazier/easier version. However, I am still curious as to how I would go about assigning a key value pair to a double dollar sign variable.

Any help would be greatly appreciated! I have the simple code working now, but would like to implement this new code to be more dynamic and allow for more queries as needed without hassle.

Thanks!

Josh

2

There are 2 answers

3
Wrikken On BEST ANSWER

${$name}[$key]

But I do not like to create 'unknown' variable, as in variables whose name is not in the code... What if the name is 'key','db','_GET','compQuery' etc? All hell breaks loose...

0
icktoofay On

In this line:

$name = array();

You're overwriting $name. You probably meant to write to $$name:

$$name = array();