I have the following array (called $example_array
below):
array(3) {
["id"]=> string(4) "123"
["name"]=>
array(1) {
["first"]=> string(3) "pete"
["last"]=> string(3) "foo"
}
["address"]=>
array(1) {
["shipping"]=>
array(1) {
["zip"]=> string(4) "1234"
["country"]=> string(4) "USA"
}
}
}
I would like a function that I can run against arrays like this and look for a match. Here are the searches that I would like to be able to perform:
// These should return true:
search( $example_array, array( 'id' => '123' ) );
search( $example_array, array( 'name' => array( 'first' => 'pete' ) );
search( $example_array, array( 'address' => array( 'shipping' => array( 'country' => 'USA' ) ) );
// These don't have to return true:
search( $example_array, array( 'first' => 'pete' ) );
search( $example_array, array( 'country' => 'USA' ) );
Is there a PHP internal function that I can use or will I have to code something myself?
function search($array, $b) {
$ok = true;
foreach ($b as $key => $value) {
if (!isset($array[$key])) { $ok = false; break; }
if (!is_array($value))
$ok = ($array[$key] == $value);
else
$ok = search($array[$key], $value);
if ($ok === false) break;
}
return $ok;
}
Here's the test script.
Hope this function helps:
public function matchArray(&$arrayToSearch, $valueToMatch = array()){
if(!is_array($valueToMatch))
$valueToMatch = array($valueToMatch);
$exists = false;
$indexToMatch = array_keys($valueToMatch);
foreach($indexToMatch as $ind){
if(array_key_exists($ind, $arrayToSearch)){
$valToMatch = $valueToMatch[$ind];
$value = $arrayToSearch[$ind];
$valType = gettype($value);
$valToMatch = $valueToMatch[$ind];
if($valType == gettype($valToMatch) || is_numeric($valToMatch)){
if($valType == 'array'){
$exists = $this->matchArray($value, $valToMatch);
} else if(($valType == 'string' || is_numeric($valToMatch)) && $valToMatch == $value) {
$exists = true;
} else {
$exists = false;
break;
}
}
}
}
return $exists;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With