Home >Backend Development >PHP Tutorial >How to Transform a Database Row Array into an Associative Array in PHP?

How to Transform a Database Row Array into an Associative Array in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-27 13:19:09675browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn