Using Array Variables to Generate Associative Array
When working with multidimensional arrays where each row contains two values, it is often desirable to create an associative array using one column as keys and the other as values. However, attempts like $dataarray[] = $row['id'] => $row['data']; may prove unsuccessful.
To address this issue, a more straightforward approach involves using the array variable as the key index. Here's how it works:
1 |
|
This code essentially assigns the value of $row['id'] to a key in the $dataarray, with the value $row['data'] being stored in that key's associated element.
For example, given the following result set:
1 2 3 4 5 |
|
Using the $dataarray[$row['id']] = $row['data']; technique would produce the desired associative array:
1 2 3 4 5 |
|
The above is the detailed content of How Can I Efficiently Create an Associative Array from a Multidimensional Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!