I have a big array that contains rows as following:
Array
(
[0] => Array
(
[attribute] => gender
[value] => male
)
[1] => Array
(
[attribute] => first_name
[value] => test
)
)
I want to convert it into an associative array:
Array
(
[gender] => male
[first_name] => test
)
Is here a built-in PHP function that can do it or should I do it using a Foreach loop?
PHP has a native function call to convert two columns of data into a flat associiative array.
Call array_column()
and offer the "values" column as the second parameter and the "keys" parameter as the third parameter.
Bear in mind, if there are duplicate values (or otherwise values that will result in key collisions because of how PHP modifies certain data types to suit its data quality requirements), then some values may be unintentionally overwritten and depending on your PHP version "Deprecated" warnings may be emitted (Edge case demo).
Code: (Demo)
var_export(
array_column($array, 'value', 'attribute')
);