Home >Backend Development >PHP Tutorial >How to Transform a Database Row Array into an Associative Array in PHP?
Converting an Array of Rows into an Associative Array
When dealing with a database result set, it's common to encounter situations where you need to create an associative array with specific column values as keys and others as values. This conversion allows for efficient data access and manipulation.
To achieve this, you can use the following simple syntax:
$dataarray[$row['key_column']] = $row['value_column'];
In this example, $row['key_column'] represents the column that will be used as the key for each array element, while $row['value_column'] represents the column that will be used as the value.
Here's a revised version of your code using this approach:
while ($row = $resultSet->fetch_assoc()) { $dataarray[$row['id']] = $row['data']; }
With this modification, your code will correctly generate an associative array with keys representing the id column and values representing the data column:
[ 1 => 'one', 2 => 'two', 3 => 'three' ]
This technique provides a straightforward and efficient way to create associative arrays from sets of rows, simplifying data access and manipulation in various programming scenarios.
The above is the detailed content of How to Transform a Database Row Array into an Associative Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!