Interact with multidimensional array - PHP

1

I would like to know how to do a multidimensional array interaction without using foreach.

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

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

I want to get only the id fields. So I want a result like this: [1, 2] .

Thanks.

    
asked by anonymous 06.01.2016 / 16:38

2 answers

2

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

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

And it will be as simple as that.

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);
    
06.01.2016 / 17:01
2

I think your question does not really express what you are trying to say. In the way you describe it, you would simply do it this 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 will actually be an iteration. Without 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);
    
06.01.2016 / 16:55