Home > Backend Development > PHP Tutorial > How to Transform a Row Array into an Associative Array Using Two Columns?

How to Transform a Row Array into an Associative Array Using Two Columns?

Linda Hamilton
Release: 2024-12-14 14:53:10
Original
701 people have browsed it

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:

  1. Initialize an Empty Array:
    Start by creating an empty array to store the associative array.
  2. Iterate Over Row Data:
    Loop through each row in the original array.
  3. 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'];
    Copy after login

Example

Consider the following MySQL result set:

$resultSet = [
    ['id' => 1, 'data' => 'one'],
    ['id' => 2, 'data' => 'two'],
    ['id' => 3, 'data' => 'three']
];
Copy after login

By applying the above approach, we can generate the following associative array:

[
    1 => 'one',
    2 => 'two',
    3 => 'three'
]
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template