Good day. The cost of the task is to choose from the array id by name $data = "Калуга" the array itself:

 $getAccount = [groups] => Array ( [0] => Array ( [id] => 48699 [name] => Калуга ) [1] => Array ( [id] => 48702 [name] => Краснодар2 ) [2] => Array ( [id] => 48705 [name] => Ростов-на -Дону ) [3] => Array ( [id] => 48708 [name] => Архангельск ) [4] => Array ( [id] => 48711 [name] => Пермь ) [5] => Array ( [id] => 48714 [name] => Белгород ) ) 

my example doesn't work:

 $get = array(); foreach ($getAccount["groups"] as $key => $val) { if($get[$key]["name"] == $data){ return $get[$key]["id"] = $val; } } echo '<pre>'.print_r($get, true).'</pre>'; die(); 

I would appreciate if you point to an error

  • or use array_filter () - splash58

2 answers 2

you use value as an index, while it is a subarray, therefore

 foreach ($getAccount["groups"] as $k =>$value) { if((string)$getAccount["groups"][$k]["name"] == (string)$data){ $id_group = $getAccount["groups"][$k]["id"]; break; } } 

or so

 foreach ($getAccount["groups"] as $value) { if((string) $value["name"] == (string)$data){ $id_group = $value["id"]; break; } } 
  • Thank you very much !! I haven’t written to php for a long time ... the correct question was added - Ivan Triumphov
  • yes there is nothing - everything is very simple here - splash58
  • and if there are several "kalugs", then the result will be the first entry, should it be? - Invision
  • @Invision to answer the question whether it should be so difficult for me, focused on break in the code, and it’s easy to remake into an array :) - splash58

Implementation in PHP> = 5.5 without using foreach

 $groupId = array_search($data, array_column($getAccount['groups'], 'name', 'id')); 

Result

 48699 
  • on the local computer works, on the host Fatal error: Call to undefined function array_column () apparently the old php version on hosting - Ivan Triumphov