Jump to content

[SOLVED] Array Locate


wolves

Recommended Posts

Hi, I trying to build a function that can locate and return the key of an array....

 

something like

 

$haystack = array(  
  array('id' => 1, 'name' => 'fernando', 'age' => 20),
  array('id' => 2, 'name' => 'jean', 'age' => 18),
  array('id' => 3, 'name' => 'paul', 'age' => 23),
  array('id' => 4, 'name' => 'bob', 'age' => 20),
  array('id' => 5, 'name' => 'richard', 'age' => 28), 
);

echo ArrayLocate(array('age' => 18),$haystack);

-> 1...

1 is the key of haystack that contain age = 18....

 

echo ArrayLocate(array('age' => 20),$haystack);

-> Array(0,3)...

0,3 are keys of haystack that contain age = 20...

 

echo ArrayLocate(array('age' => 20, 'name' => 'bob'),$haystack);

-> 3...

3 is the key of haystack that contain age = 20 and name = 'bob'....

 

tks

 

Link to comment
https://forums.phpfreaks.com/topic/61354-solved-array-locate/
Share on other sites

try

<?php
function ArrayLocate($srch,$haystack) {
$out = array();
foreach ($srch as $k => $v) {
	foreach ($haystack as $key => $h) {
		if ($h[$k] == $v) $out[] = $key;
	}

}
return $out;
}
$haystack = array(  
  array('id' => 1, 'name' => 'fernando', 'age' => 20),
  array('id' => 2, 'name' => 'jean', 'age' => 18),
  array('id' => 3, 'name' => 'paul', 'age' => 23),
  array('id' => 4, 'name' => 'bob', 'age' => 20),
  array('id' => 5, 'name' => 'richard', 'age' => 28), 
);
$z = ArrayLocate(array('age' => 20),$haystack);
print_r($z);
?>

Link to comment
https://forums.phpfreaks.com/topic/61354-solved-array-locate/#findComment-305326
Share on other sites

some modifications....

<?php
function ArrayLocate($srch,$haystack) {
$out = array();
$cant = array();
foreach ($srch as $k => $v) {
	foreach ($haystack as $key => $h) {
		if (($h[$k] == $v) && !in_array($key,$cant))
		 $out[$key] = $key;
		else {
		 $cant[] = $key;
		 if(isset($out[$key]))
		   unset($out[$key]);
		}
	}

}
return $out;
}
$haystack = array(  
  array('id' => 1, 'name' => 'fernando', 'age' => 20,'adr' => 'blue'),
  array('id' => 2, 'name' => 'fernando', 'age' => 20,'adr' => 'green'),
  array('id' => 3, 'name' => 'jean', 'age' => 18),
  array('id' => 4, 'name' => 'paul', 'age' => 23),
  array('id' => 5, 'name' => 'bob', 'age' => 20),
  array('id' => 6, 'name' => 'richard', 'age' => 28), 
);
$z = ArrayLocate(array('name' => 'fernando','adr' => 'green'),$haystack);
print_r($z); 
?>

Link to comment
https://forums.phpfreaks.com/topic/61354-solved-array-locate/#findComment-305330
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.