How to make a foreach for an array of arrays?

Asked

Viewed 4,546 times

7

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

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

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

Note: preferably the most effective way to do.

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"
  }
}

Online example here

  • 2

    I never paid much attention to that role, but it’s much better than writing all those lines.

  • 2

    Excellent response Sergio +1

  • The example disappeared @Sergio

  • 1

    @Jorgeb. Sad. I’ll put back later, from a more credible website... thank you!

3

You can do it like 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 the array_column http://php.net/manual/en/function.array-column.php

  • The array-column works even with this array like this?

  • 1

    I haven’t tried it because I have 5.3 installed, but according to the documentation it works yes.

  • @Manuelgerardopereira array_column for earlier versions than php 5.5 : https://github.com/ramsey/array_column

2

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 ;)

Browser other questions tagged

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