Compare nested foreach variables in php without globals?
I have multiple foreach's parsing data that I need to compare with each other. For instance:
foreach ($xml_string->xpath('//location') as $character) {
$xml_name = $character->earthname;
$compare_remote = strtolower(preg_replace("/[^a-zA-Z0-9 ]/", "", $xml_name));
}
foreach ( $whatever as $key => $value ) {
foreach ($value as $pkey){
$value_name = $pkey["spacename"];
$compare_local = strtolower(preg_replace("/[^a-zA-Z0-9]/", '', $value_name));
}
}
How can I loop through both sets of foreach to compare all the values in 开发者_如何学编程$compare_remote
with the values in $compare_local
, I will probably be using levenshtein()
, but for the sake of this example anything will do.
foreach ($xml_string->xpath('//location') as $character) {
$xml_name = $character->earthname;
$compare_remote = strtolower(preg_replace("/[^a-zA-Z0-9 ]/", "", $xml_name));
foreach ( $whatever as $key => $value ) {
foreach ($value as $pkey){
$value_name = $pkey["spacename"];
$compare_local = strtolower(preg_replace("/[^a-zA-Z0-9]/", '', $value_name));
if( $compare_remote==$compare_local) echo "match";
}
}
}
Without knowing what it is your comparing, you could use an associative array outside both loops as key / value lookups. If there is a common key then you can operate on the same values that were evaluated by both loops. Ideally I know you want to iterate over both at the same time, but this is a possibility that results in one evaluated set of data. Unique keys are preserved.
$compare[];
foreach ($xml_string->xpath('//location') as $character) {
$xml_name = $character->earthname;
$compare[strtolower(preg_replace("/[^a-zA-Z0-9 ]/", "", $xml_name))];
}
foreach ( $whatever as $key => $value ) {
foreach ($value as $pkey){
$value_name = $pkey["spacename"];
$compare[strtolower(preg_replace("/[^a-zA-Z0-9]/", '', $value_name))];
}
}
精彩评论