Home >Backend Development >PHP Tutorial >How Can I Efficiently Create an Associative Array from a Multidimensional Array in PHP?

How Can I Efficiently Create an Associative Array from a Multidimensional Array in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-17 08:29:25476browse

How Can I Efficiently Create an Associative Array from a Multidimensional Array in PHP?

Using Array Variables to Generate Associative Array

When working with multidimensional arrays where each row contains two values, it is often desirable to create an associative array using one column as keys and the other as values. However, attempts like $dataarray[] = $row['id'] => $row['data']; may prove unsuccessful.

To address this issue, a more straightforward approach involves using the array variable as the key index. Here's how it works:

$dataarray[$row['id']] = $row['data'];

This code essentially assigns the value of $row['id'] to a key in the $dataarray, with the value $row['data'] being stored in that key's associated element.

For example, given the following result set:

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

Using the $dataarray[$row['id']] = $row['data']; technique would produce the desired associative array:

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

The above is the detailed content of How Can I Efficiently Create an Associative Array from a Multidimensional 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