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:
$dataarray[$row['id']] = $row['data'];
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:
$resultSet = [ ['id' => 1, 'data' => 'one'], ['id' => 2, 'data' => 'two'], ['id' => 3, 'data' => 'three'] ];
Using the $dataarray[$row['id']] = $row['data']; technique would produce the desired associative array:
[ 1 => 'one', 2 => 'two', 3 => 'three' ]
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!