0
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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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!
2

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.

2 Comments

Any particular reason not to use extract()?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.