LStarky LStarky - 29 days ago 15
PHP Question

Convert array of key-value pairs into associative array without using column names

I have an array from a database query:

Array (
[0] => Array ( [div_id] => 21 [div_name] => "Alphabet" )
[1] => Array ( [div_id] => 16 [div_name] => "Elementary" )
[2] => Array ( [div_id] => 19 [div_name] => "Preschool" )
[3] => Array ( [div_id] => 20 [div_name] => "Secondary" )
)


I would like to transform it into:

Array (
[21] => "Alphabet"
[16] => "Elementary"
[19] => "Preschool"
[20] => "Secondary"
)


However, I can't use the key names. I need to reference them as the first and second columns, since in my context I can't control the keys of the source data. I need to use the same algorithm on data with different key names, for example:

Array (
[0] => Array ( [unknown_id] => 21 [random] => "Alphabet" )
[1] => Array ( [unknown_id] => 16 [random] => "Elementary" )
[2] => Array ( [unknown_id] => 19 [random] => "Preschool" )
[3] => Array ( [unknown_id] => 20 [random] => "Secondary" )
)


The question is very similar to Convert array of key-value pairs into associative array but that had [0] and [1] for the keys, and I have text keys but still need to reference the first and second items of the arrays.

Answer

You could do it like this:

$indexed = array_map('array_values', $data);
$res = array_combine(array_column($indexed, 0), array_column($indexed, 1));

Or with the 3rd argument of array_column:

$res = array_column(array_map('array_values', $data), 1, 0);