Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
foreach ($topicarray as $key=>$value){
    $files = mysql_query("mysqlquery");

    while($file = mysql_fetch_array($files)){ extract($file);
        $topicarray[$value] = array( array($id=>$title)
                      );
       }
    }

The first foreach loop is providing me with an array of unique values which forms a 1-dimensional array.

The while loop is intended to store another array of values inside the 1-dimensional array.

When the while loop returns to the beginning, it is overwriting it. So I only ever get the last returned set of values in the array.

My array ends up being a two dimensional array with only one value in each of the inner arrays.

Feels like I'm missing something very basic here - like a function or syntax which prevents the array from overwriting itself but instead, adds to the array.

Any ideas?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

Step 1. Replace $topicarray[$value] with $topicarray[$value][]
Step 2. ???
Step 3. Profit

share|improve this answer
    
Can't believe I didn't try that. I think I got lost in the array, forgetting the fundamentals of how to start an array! –  chocolatecoco Jun 20 '12 at 22:26

Make $topicarray[$value] an array of rows, instead of one row. Also, don't use extract here.

foreach ($topicarray as $key => $value) {
    $rows = array();
    $files = mysql_query("mysqlquery");

    while($file = mysql_fetch_array($files)) {
        $rows[] = array($file['id'] => $file['title']);
    }

    $topicarray[$value] = $rows;
}

Also, you should switch to PDO or MySQLi.

share|improve this answer
    
Thanks for this, this works too! –  chocolatecoco Jun 20 '12 at 22:28
    
Any particular reason not to use extract()? –  chocolatecoco Jun 20 '12 at 22:29
    
@chocolatecoco: It could overwrite random variables in your code if you add columns to the query/table later on, and it's just not as obvious or as efficient as accessing them through array indices. –  minitech Jun 20 '12 at 22:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.