note 88596 modified in function.array-intersect by danbrown
| From: | danbrown@php.net | Date: | Fri, 30 Jan 2009 18:00:30 +0000 |
| Subject: | note 88596 modified in function.array-intersect by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-149993@lists.php.net to get a copy of this message | ||
Given a multidimensional array that represents AND/OR relationships (example below), you can use a
recursive function with array_intersect() to see if another array matches that set of relationships.
For example: array( array( 'red' ), array( 'white', 'blue' ) )
represents "red OR ( white AND blue )". array( 'red', array( 'white',
'blue' ) ) would work, too, BTW.
If I have array( 'red' ) and I want to see if it matches the AND/OR array, I use the
following function. It returns the matched array,
but can just return a boolean if that's all you need:
<?php
$needle = array( array( 'red' ), array( 'white', 'blue' ) );
$haystack = array( 'red' );
function findMatchingArray( $needle, $haystack ) {
foreach( $needle as $element ) {
$test_element = (array) $element;
if( count( $test_element ) == count( array_intersect( $test_element, $haystack ) ) ) {
return $element;
}
}
return false;
}
?>
Pretty tough to describe what I needed it to do, but it worked. I don't know if anyone else
out there needs something like this, but hope this helps.
--was--
Given a multidimensional array that represents AND/OR relationships (example below), you can use a
recursive function with array_intersect() to see if another array matches that set of relationships.
For example: array( array( 'red' ), array( 'white', 'blue' ) )
represents "red OR ( white AND blue )". array( 'red', array( 'white',
'blue' ) ) would work, too, BTW.
If I have array( 'red' ) and I want to see if it matches the AND/OR array, I use the
following function. It returns the matched array, but can just return a boolean if that's all
you need:
$needle = array( array( 'red' ), array( 'white', 'blue' ) );
$haystack = array( 'red' );
function findMatchingArray( $needle, $haystack ) {
foreach( $needle as $element ) {
$test_element = (array) $element;
if( count( $test_element ) == count( array_intersect( $test_element, $haystack ) ) ) {
return $element;
}
}
return false;
}
Pretty tough to describe what I needed it to do, but it worked. I don't know if anyone else
out there needs something like this, but hope this helps.
http://php.net/manual/en/function.array-intersect.php