Interacting with multidimensional array - PHP

Asked

Viewed 625 times

1

I would like to know how to interact with the multidimensional array without using foreach.

$arr1 = array('id' => 1, 'nome' => 'Joao');
$arr2 = array('id' => 2, 'nome' => 'Maria');

$arrTotal = array($arr1, $arr2);

I only want to take the fields id. So I want a result as follows: [1, 2].

Thanks.

  • 1

    And why not array($arr1['id'], $arr2['id']); ?

  • You want to add the id of all arrays?

2 answers

2

I think your question doesn’t really express what you’re trying to say.
The way you describe it, you’d just do it that way:

$arr1 = array('id' => 1, 'nome' => 'Joao');
$arr2 = array('id' => 2, 'nome' => 'Maria');

$arrTotal = array($arr1['id'], $arr2['id']);

However, perhaps $arr1 and $arr2 are elements of another array, such as this:

$map = array(
    array('id' => 1, 'nome' => 'Joao'),
    array('id' => 2, 'nome' => 'Maria'),
    array('id' => 7, 'nome' => 'Pedro'),
);

With this structure, your question makes sense, because there really will be an iteration. No foreach:

$map = array(
    array('id' => 1, 'nome' => 'Joao'),
    array('id' => 2, 'nome' => 'Maria'),
    array('id' => 7, 'nome' => 'Pedro'),
);

$result = array_map(function($a) { return $a['id']; }, $map);

2


If you are using PHP 5.5 or higher, you can take advantage of the function array_column.

$result = array_column($total_array, 'id');

And so simple will have the expected result.

For versions prior to 5.5, you can create the array_column function yourself

if(!function_exists("array_column")) {
    function array_column($array,$column_name) {
       return array_map(function($element) use ($column_name) {
          return $element[$column_name];
       }, $array);
    }
}

Or just use the array_map

$result = array_map(function($item) {
   return $item['id']; 
}, $arrayTotal);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.