How to make a foreach for an array of arrays?

7

How can I make a foreach for an array of arrays like this:

array
(
    [option1] => 2
    [option2] => array
                 (
                     [name] => "ola mundo"
                     [id]   => "123456"
                     ...
                 )
    ...
)

The array can range from options and I want to print all the "name" fields found.

Note: Preferably the most effective way to do it.

    
asked by anonymous 03.10.2014 / 16:55

3 answers

13

PHP has an interesting function that applies another function to all members of an array.

It's called array_walk_recursive

Test like this:

$array = array(array('nome' => 'Luis', 'id' => 1), array('nome' => 'Rui', 'id' => 2));

$nomes = array();
array_walk_recursive($array, function ($item, $key) {
    global $nomes;
    if ($key == 'nome') $nomes[] = $item;
});

var_dump($nomes);

// resultado:
array(2) {
  [0]=>
  string(4) "Luis"
  [1]=>
  string(3) "Rui"
}

Online example here

Another idea is to make a recursive function that passes information to itself. The result is a multidimensional array.

$array = array(array('nome' => 'Luis', 'id' => 1), array('nome' => 'Rui', 'id' => 2));

function recurse($array, $retorno){

    foreach ($array as $key => $item) {
        if (is_array($item)) $interno[] = recurse($item, $retorno);
        else if ($key == 'nome') $interno[] = $item;
    }
    if (count($retorno)) $retorno = array_merge($interno, $retorno);
    else $retorno = $interno;
    return $retorno;
}

var_dump(recurse($array, array()));

// resultado:
array(2) {
  [0]=>
  array(1) {
    [0]=>
    string(4) "Luis"
  }
  [1]=>
  array(1) {
    [0]=>
    string(3) "Rui"
  }
}

Example online here

    
03.10.2014 / 17:05
2

You can do this:

   $ar = array
    (
        [option1] => 2
        [option2] => array
                     (
                         [name] => "ola mundo"
                         [id]   => "123456"
                         ...
                     )
        ...
    )

foreach($ar as $value)
{
   if(!is_array($value))
       continue;

   foreach($value as $v_key =>$v_value)
   {
        if($v_key=="name")
        {
           $nomes[] = $v_value;

        //se nesta array existir apenas uma chave nome para este loop e salta para o´
        //mais exterior
          continue 2;
        }


   }
}

If you have php 5.5.0 you can use array_column link

    
03.10.2014 / 17:07
2

If it is an array with only two dimensions, such as the output of a database for example, 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 .

Remembering that array_column is one of the new features of php 5.5, but this function can be easily used in previous versions using a implementation in own php .

If your array has even more dimensions, another way is to use a RecursiveIteratorIterator 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 .

    

30.10.2014 / 16:57