php – How to find a value in an array with a specific structure

Question:

I need to find the position of an array within another, in the following structure:

array{
  [0]=>{
    ["id"]=>"5744"
    ["fk"]=>"7"
    ["nome"]=>"Nivel 1"
    ["created"]=>"2014-04-30 16:54:14"
    ["modified"]=>NULL
    ["user_created"]=>NULL
    ["sadmin"]=>"N"
    ["color"]=>NULL
  }
  [1]=>{
    ["id"]=>"5745"
    ["fk"]=>"5744,7"
    ["nome"]=>"Nível 2"
    ["created"]=>"2014-04-30 16:56:21"
    ["modified"]=>NULL
    ["user_created"]=>NULL
    ["sadmin"]=>"N"
    ["color"]=>NULL
  }
  [2]=>{
    ["id"]=>"5746"
    ["fk"]=>"5745,5744,7"
    ["nome"]=>"Nível 3"
    ["created"]=>"2014-04-30 16:57:15"
    ["modified"]=>NULL
    ["user_created"]=>NULL
    ["sadmin"]=>"N"
    ["color"]=>NULL
  }
}

As an example: I have the value 5746 and I have to search through it, that is, I need everything found in position 2 of the array.

I'm editing to add important information that I ended up not mentioning:

the array is extremely large, and I will need to perform this search many times on this same array, so I need a solution without foreach , which does a direct search without me having to go through the entire array.

Answer:

I'm not experienced in php but I think this can help.

Assuming the input array is what you passed named $valores :

$valores = array(
  0 => array(
    "id" =>"5744",
    "fk" =>"7",
    "nome" =>"Nivel 1",
    "created" =>"2014-04-30 16:54:14",
    "modified" =>NULL,
    "user_created" =>NULL,
    "sadmin" =>"N",
    "color" =>NULL),

  1 => array(
    "id"=>"5745",
    "fk"=>"5744,7",
    "nome"=>"Nível 2",
    "created"=>"2014-04-30 16:56:21",
    "modified"=>NULL,
    "user_created"=>NULL,
    "sadmin"=>"N",
    "color"=>NULL),

  2 => array(
    "id"=>"5746",
    "fk"=>"5745,5744,7",
    "nome"=>"Nível 3",
    "created"=>"2014-04-30 16:57:15",
    "modified"=>NULL,
    "user_created"=>NULL,
    "sadmin"=>"N",
    "color"=>NULL)
);

And to look up the ID, you can use a simple for :

// Busca pelo elemento de ID 5746

foreach ($valores as &$valor) 
{
    if($valor["id"] == "5746")
    {
        // Array encontrado.
        print_r($valor);
    }
}
Scroll to Top