-1

I have an array of associative arrays like this:

$array = [
    ["foobar" => "asd"],
    ["foobar" => "abvc"],
    ["foobar" => "test123"],
];

I would like to have the column values used as keys and values in the end result.

[
    'asd' => 'asd',
    'abvc' => 'abvc',
    'test123' => 'test123',
];

I tried using array_flip() while looping over, but I did not manage to get the desired output.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136

2 Answers2

2

Use array_column to get all the nested foobar values. Then use array_combine to make an associative array using that as both the keys and values.

$values = array_column($array, 'foobar');
$result = array_combine($values, $values);
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

There is no need to call array_combine(). Tell array_column() to assign foobar column values as values (2nd param) and keys (3rd param).

Code: (Demo)

var_export(
    array_column($array, 'foobar', 'foobar')
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136