下面是一個使用簡單而又重複的另一種方法。您可以設置所需的匹配數量,並且可以找到任何屬性的匹配項(沒有任何固定的)。我將它包裝在一個類中以保留所有內容:
<?php
class MatchFind {
// This can be set to any number of matches desired
const ELEMENTS_TO_FIND = 2;
public static function count ($aObjs) {
// Cannot compare elements unless there are 2
if (sizeof($aObjs) <= 1) {
return 0;
}
// Get the top element from the array
$oTop = array_shift($aObjs);
$aTopProps = (array) $oTop->Job;
// Get the number of matches, moving from end to start,
// removing each match from the array
$iMatchObjs = 0;
for ($n = sizeof($aObjs); $n > 0; $n--) {
$oCompare = $aObjs[$n-1];
$iMatch = 0;
foreach ((array) $oCompare->Job as $sKey => $sValue) {
if (isset($aTopProps[$sKey]) && $aTopProps[$sKey] === $sValue) {
++$iMatch;
}
}
if ($iMatch >= self::ELEMENTS_TO_FIND) {
unset($aObjs[$n-1]);
++$iMatchObjs;
}
}
reset($aObjs);
return ($iMatchObjs + self::count($aObjs));
}
}
// Declare the objects
$aAllObjs = [
(object)[ 'Job' => (object)['ID' => 123,
'Line' => 'Shirt',
'Color' => 'Blue'] ],
(object)[ 'Job' => (object)['ID' => 456,
'Line' => 'Jeans',
'Color' => 'Blue'] ],
(object)[ 'Job' => (object)['ID' => 789,
'Line' => 'Jeans',
'Color' => 'Blue'] ],
];
echo MatchFind::count($aAllObjs);
任何兩個值,或者特別是Line和Color? –