Return values from an array after a given key

2

I have an array with about 100 positions this way:

[
  {
      "1":{
         "id":1262,
         "nome":"Fulano",
         "sobrenome":"de Tal"
      }
  },
  {
      "2":{
         "id":1263,
         "nome":"Beltrano",
         "sobrenome":"da Silva"
      }
  },
...
]

How do I return all values after key 2?

Thanks in advance for your help!

    
asked by anonymous 10.06.2014 / 17:16

2 answers

2

Print from the key 3 being greater than key 2

<?php
$array = [
         ["1" => ["id"=>1262,"nome"=>"Fulano","sobrenome"=>"de Tal"]],
         ["2" => ["id"=>1263,"nome"=>"Beltrano","sobrenome"=>"da Silva"]],
         ["3" => ["id"=>1264,"nome"=>"Fulano 1","sobrenome"=>"de Tal1"]],
         ["4" => ["id"=>1267,"nome"=>"Fulano 2","sobrenome"=>"de Tal2"]]
         ];


foreach($array as $index => $value){
    foreach($value as $index1 => $value1){
        if ((int)$index1 > 2){
            echo "N&uacute;mero:".$index1.' '. $value1["id"].' '.$value1["nome"]. ' '. $value1["sobrenome"];
            echo '<br>';
        }
    }   
}
    
10.06.2014 / 17:49
1

What if I said that you can filter this array without iterating it, at least not in the conventional way?

Nothing against the solution presented but you should avoid nested loops at all costs. This is extremely damaging to Application performance.

Translating your problem into smaller parts, you want to find a certain index and return everything after it.

When you do this, you are removing some items from the original array, so you are filtering it. And if you're filtering an array, array_filter () is the solution.

You will need a customized callback as there is no native function to do what you need. The "essence" of this callback will be based on the key () function:

$filtered = array_filter(

    $array,

    function( $current ) {

        return ( key( $current ) > 2 );
    }
);

This produces:

Array
(
    [2] => Array
        (
            [3] => Array
                (
                    [id] => 1264
                    [nome] => Fulano 1
                    [sobrenome] => de Tal1
                )

        )

    [3] => Array
        (
            [4] => Array
                (
                    [id] => 1267
                    [nome] => Fulano 2
                    [sobrenome] => de Tal2
                )

        )

)
  

Note: The focus of the response is to filter the array and not unidimensionalize it, an extremely important secondary and subsequent task to keep the routine away from nested loops.

    
10.06.2014 / 20:36