recursive array search
-
Hi there, I have a piece of code to search through a multidimensional array and return the keys of successful hits... The problem is that I can see it has checked all though the array (the echo "@"; shows an @ for each element of the array) but the matches are not returned, the array contains at least 30 "status" fields. Can anyone tell me where I'm going wrong.. Thanks Here is the code:
$haystack = $server1 = $tx->extractTable();
$needle = 'Status';
$index = null;$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);while($it->valid()) { if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) { return $aIt->key(); echo $aIt->key(); } echo "@"; $it->next(); } return false;
-
Hi there, I have a piece of code to search through a multidimensional array and return the keys of successful hits... The problem is that I can see it has checked all though the array (the echo "@"; shows an @ for each element of the array) but the matches are not returned, the array contains at least 30 "status" fields. Can anyone tell me where I'm going wrong.. Thanks Here is the code:
$haystack = $server1 = $tx->extractTable();
$needle = 'Status';
$index = null;$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);while($it->valid()) { if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) { return $aIt->key(); echo $aIt->key(); } echo "@"; $it->next(); } return false;
-
nhsal69 wrote:
return $aIt->key();
echo $aIt->key();
Is there any reason why you are returning and then outputing? The output code (echo) is unreachable.
If at first you don't succeed, you're not Chuck Norris.
-
Then there would appear to be something wrong with your logic.
nhsal69 wrote:
if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle))
If at first you don't succeed, you're not Chuck Norris.
Ok, I've been staring at that for ages and my logic has vanished... I re wrote it to this the below.... Only problem is that I still don't get a valid response.. the array is of the form : [1] => Array ( [Name ] => Aberdeen [Status ] => Ready [Location ] => [Jobs ] => 0 [Model ] => HPUniversalPrintingPCL6 [Comment ] => PRINT_EARL The correct number of "@" are retuned so it's performing the correct number of itterations, but no giving me the results... I should have mentioned that I'm completely new to PHP and am kinda winging it.... Start of code chunk $it = new RecursiveIteratorIterator( new RecursiveArrayIterator($server1)); echo ""; foreach ($it as $key=>$val) { echo "@"; if ($val == "PRINT_EARL") { echo ""; echo ""; echo ""; echo ""; } Else echo $key.":".$val."\n"; } End of code chunk -- Modified Monday, May 3, 2010 10:51 AM
"; echo $key; echo "
"; echo $val; echo "