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
Release: 2024-12-17 08:29:25
Original
409 people have browsed it

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:

1

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

Copy after login

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:

1

2

3

4

5

$resultSet = [

    ['id' => 1, 'data' => 'one'],

    ['id' => 2, 'data' => 'two'],

    ['id' => 3, 'data' => 'three']

];

Copy after login

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

1

2

3

4

5

[

    1 => 'one',

    2 => 'two',

    3 => 'three'

]

Copy after login

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!

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