在没有全局变量的PHP中比较嵌套的foreach变量?

时间:2011-04-23 04:24:33

标签: php foreach compare

我有多个foreach的解析数据,我需要相互比较。例如:

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));

 }
}

如何循环遍历两组foreach以将$compare_remote中的所有值与$compare_local中的值进行比较,我可能会使用levenshtein(),但为了这个目的任何事情都可以。

2 个答案:

答案 0 :(得分:1)

    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";
          }
        }

 }

答案 1 :(得分:1)

在不知道比较的情况下,您可以在两个循环外部使用关联数组作为键/值查找。如果存在公共密钥,则可以对两个循环评估的相同值进行操作。理想情况下,我知道您希望同时迭代两者,但这可能会产生一组经过评估的数据。保留了唯一的密钥。

$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))];

 }
}