Let's assume I have an array of elements, which are arrays themselves, like so:
$array = [
['foo' => 'ABC', 'bar' => 'DEF'],
['foo' => 'ABB', 'bar' => 'DDD'],
['foo' => 'BAC', 'bar' => 'EFF'],
];
To set the values of the foo
field as the key of the array I could do this:
foreach ($array as $element) {
$new_array[$element['foo']] = $element;
}
$array = $new_array;
The code is naturally trivial, but I've been wondering whether there's an in-built that can do the same for me.
Notice array_column
can get index as well (third argument):
mixed $index_key = NULL
So just use as:
array_column($array, null, 'foo');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With