How To array_search in Multi Dimensional Array?

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
bgundal88
Forum Newbie
Posts: 6
Joined: Thu Dec 22, 2011 10:42 am

How To array_search in Multi Dimensional Array?

Post by bgundal88 »

Hi, I have multi dimensional array like this :

Code: Select all

$families = array
  (
  "Griffin"=>array
  (
  "Peter",
  "Lois",
  "Megan"
  ),
  "Quagmire"=>array
  (
  "Glenn"
  ),
  "Brown"=>array
  (
  "Cleveland",
  "Loretta",
  "Junior"
  )
  );
and I have no idea how to display "Griffin" when "Peter" entered as variable. or "Brown" when "Loretta" entered.

I thought by using array_search function will help, but array_search seems need to be 'modified' when it's dealing with multi dimensional arrays.

please help… thanks!
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: How To array_search in Multi Dimensional Array?

Post by tr0gd0rr »

You'll have to iterate and look for the value. Is it always only 2 levels deep? If it could be deeper, you'll need a recursive find.
bgundal88
Forum Newbie
Posts: 6
Joined: Thu Dec 22, 2011 10:42 am

Re: How To array_search in Multi Dimensional Array?

Post by bgundal88 »

Yes, bro. Only 2 levels deep. Nothing else. Do you have some sample code to do it?
phpHappy
Forum Commoner
Posts: 33
Joined: Wed Oct 26, 2011 1:58 pm

Re: How To array_search in Multi Dimensional Array?

Post by phpHappy »

Code: Select all

<?php
$input="Glenn";
$output='';
$families = array
  (
  "Griffin"=>array
  (
  "Peter",
  "Lois",
  "Megan"
  ),
  "Quagmire"=>array
  (
  "Glenn"
  ),
  "Brown"=>array
  (
  "Cleveland",
  "Loretta",
  "Junior"
  )
  );

$keys=array_keys($families);
$num=count($keys);
$count=0; while($count<=$num-1) {
$count2=0;
$find=$keys[$count];
while(!empty($families[$find][$count2])) {
if($families[$find][$count2] == $input) {
    $output=$keys[$count];
	echo $input.' is '.$input.' '.$output.' is phpHappy';
	$count=$num+2; break; }
$count2++; }
$count++;  }
?>
bgundal88
Forum Newbie
Posts: 6
Joined: Thu Dec 22, 2011 10:42 am

Re: How To array_search in Multi Dimensional Array?

Post by bgundal88 »

it works!! many thanks, phphappy! I love you!
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: How To array_search in Multi Dimensional Array?

Post by tr0gd0rr »

Woah, buddy, that is a lot of code! Try this:

Code: Select all

function lookupSurname($families, $firstName) {
	foreach ($families as $surname => $names) {
		if (in_array($firstName, $names)) {
			return $surname;
		}
	}
	return null;
}

echo lookupSurname($families, 'Junior'); // Brown
Post Reply