Search Keys in array of arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Search Keys in array of arrays

Post by anjanesh »

Code: Select all

$arr=array(
"Mainkey1"=>array("Name"=>"name1","Occurred"=>0),
"Mainkey2"=>array("Name"=>"name2","Occurred"=>0),
"Mainkey3"=>array("Name"=>"name3","Occurred"=>0),
"Mainkey4"=>array("Name"=>"name4","Occurred"=>0)
);
$arr["Mainkey3"]["Occurred"]=1;
print_r(array_keys($arr,"1"));
returns FALSE. How do search for keys in sub-arrays ?
Thanks
swdev
Forum Commoner
Posts: 59
Joined: Mon Oct 25, 2004 8:04 am

Post by swdev »

I assume you want to find the main key for all those arrays that have a valued for the 'Occurred' key equal to 1.

The [php_man]array_key[/php_man] function only searches a 1 dimensional array. Therefore you need to step through each main key, and use the array_key function on the resulting sub-array.

Code: Select all

<?php
  $arr=array(
    'Mainkey1'=>array('Name'=>'name1','Occurred'=>0),
    'Mainkey2'=>array('Name'=>'name2','Occurred'=>0),
    'Mainkey3'=>array('Name'=>'name3','Occurred'=>0),
    'Mainkey4'=>array('Name'=>'name4','Occurred'=>0)
    );

  $arr['Mainkey3']['Occurred']=1;

  foreach ($arr as $key => $new_array)
  {
    $found_array = array_keys($arr[$key], '1');
    if ( (is_array($found_array) == true) && (count($found_array) > 0) )
    {
      echo 'Found Main Array at Key ' . $key . ' Name = ' . $new_array['Name'] . ' Occured = ' . $new_array['Occurred'];
    }
  }
  
?>
Hope this helps
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

Thanks - I already did that - I was hoping for array_search or array_keys or some other fn to search in sub arrays too.
Post Reply