Home > Backend Development > PHP Tutorial > How to Create an Associative Array from Database Rows in PHP?

How to Create an Associative Array from Database Rows in PHP?

DDD
Release: 2024-12-16 10:51:12
Original
752 people have browsed it

How to Create an Associative Array from Database Rows in PHP?

Creating Associative Arrays from Data

When working with data from a database or other source, it can be necessary to create an associative array from a collection of rows. An associative array is a data structure that uses one column as keys and another column as values, allowing for easy retrieval of specific values based on the corresponding key.

To achieve this, we can utilize the array key-value assignment syntax in PHP. Consider the following MySQL result set:

To generate an associative array, we can loop through the result set and assign each row's 'id' value to be the array key, and the 'data' value to be the array value. Using the correct syntax:

This will result in the following associative array:

By using this approach, we can efficiently create associative arrays from data rows, providing an organized and flexible way to access values by their associated keys.

The above is the detailed content of How to Create an Associative Array from Database Rows in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template