September 30, 2019

Converting a 2D Array to a 1D Array with Specific Key-Value Pairs in PHP

In PHP, there are multiple ways to convert a 2D array into a 1D array where one column becomes the key and another column becomes the value. Below is a method using PHP’s built-in functions, which serves as a good exercise to deepen our understanding of array processing functions in PHP.

We will primarily use the array_column and array_combine functions for this purpose.

Example

Suppose we have the following 2D array:

$list = [
    0 => [
        'id' => 1001,
        'name' => 'Zhang San'
    ],
    1 => [
        'id' => 2091,
        'name' => 'Li Si'
    ]
];

We want to transform this into a 1D array like below:

$list = [
    1001 => 'Zhang San',
    2091 => 'Li Si'
];

Solution Using Built-in PHP Functions

We can achieve this transformation in one step using array_column and array_combine:

array_combine(array_column($list, 'id'), array_column($list, 'name'));

Explanation:

  • array_column($list, 'id') extracts all the ‘id’ values from the original array.
  • array_column($list, 'name') extracts all the ‘name’ values.
  • array_combine() then combines these two arrays, using the ‘id’ values as keys and the ‘name’ values as values.

Conclusion

This method is efficient and concise, leveraging PHP’s powerful array functions. It’s a great way to convert a 2D array to a 1D array, especially when you need to map specific columns to keys and values in a short and readable manner.