Home >Backend Development >PHP Tutorial >How to Transform a Row Array into an Associative Array Using Two Columns?
How to Create an Associative Array from an Array of Rows Using Two Columns as Keys and Values
When working with arrays consisting of multiple columns representing data, it is often desirable to convert them into associative arrays for efficient access. This article discusses a practical approach to achieving this conversion, specifically using MySQL result sets as an example.
The Approach
To generate an associative array from an array of rows, follow these steps:
Set Key-Value Pair:
Inside the loop, use square brackets to set the key-value pair in the associative array. The key should be the column value you want to use as the index, and the value should be the other column value. For instance:
$dataarray[$row['id']] = $row['data'];
Example
Consider the following MySQL result set:
$resultSet = [ ['id' => 1, 'data' => 'one'], ['id' => 2, 'data' => 'two'], ['id' => 3, 'data' => 'three'] ];
By applying the above approach, we can generate the following associative array:
[ 1 => 'one', 2 => 'two', 3 => 'three' ]
Conclusion
By following these steps, you can easily convert an array of rows into an associative array, making it more convenient to access data using the desired column values as keys. This approach can be particularly useful when working with database results or any other data structure with similar characteristics.
The above is the detailed content of How to Transform a Row Array into an Associative Array Using Two Columns?. For more information, please follow other related articles on the PHP Chinese website!