If it is an array with only two dimensions, as the output of a database for example, the array_column
is the simplest solution:
<?php
$array = [
['nome' => 'Luis', 'id' => 31],
['nome' => 'Rui', 'id' => 42],
['nome' => 'Joao', 'id' => 113],
['nome' => 'Joaquim', 'id' => 434],
['nome' => 'Jorge', 'id' => 503],
];
var_dump(array_column($array, 'nome'));
// Se quiser, pode aproveitar uma segunda coluna para usar como key do novo array
var_dump(array_column($array, 'nome', 'id'));
Executable example.
Recalling that the array_column
is one of the novelties of php 5.5, but this function can be easily used in previous versions using a implementation in php.
If your array has even more dimensions, another way is to use one Recursiveiteratoriterator, present in SPL of PHP.
<?php
$array = [
['nome' => 'Luis', 'id' => 1],
['nome' => 'Rui', 'id' => 2],
['nome' => 'Joao', 'id' => 3],
['nome' => 'Joaquim', 'id' => 4],
['nome' => 'Jorge', 'id' => 5],
];
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$nomes = [];
foreach ($iterator as $key => $value)
if ($key == 'nome') $nomes[] = $value;
var_dump($nomes);
Executable Example.
Ps.: Sergio, I took advantage of your Ideone ;)
I never paid much attention to that role, but it’s much better than writing all those lines.
– Manuel Gerardo Pereira
Excellent response Sergio +1
– Jorge B.
The example disappeared @Sergio
– Jorge B.
@Jorgeb. Sad. I’ll put back later, from a more credible website... thank you!
– Sergio