简体   繁体   English

搜索字符串数组以查找来自另一个数组php的字符串匹配

[英]search through array of strings for string match from another array php

I have an issue that I have two txt files, where one contains a values of what to search and second contains info from where I need to find text line which contains info from first txt file. 我有一个问题,我有两个txt文件,其中一个包含要搜索的内容的值,第二个包含我需要从中查找包含第一个txt文件中的信息的文本行的信息。 1. txt file looks like this: 1. txt文件如下所示:

 1461527867 29012520 2220097051 2596180150 29012516 2596180152 29012514 

  1. txt file looks like this: txt文件如下所示:

 <?xml version="1.0" encoding="UTF-8"?> <osm version="0.6" generator="CGImap 0.4.3 (797 thorn-02.openstreetmap.org)" copyright="OpenStreetMap and contributors" attribution="http://www.openstreetmap.org/copyright" license="http://opendatacommons.org/licenses/odbl/1-0/"> <bounds minlat="56.7042000" minlon="21.5789000" maxlat="56.7340000" maxlon="21.6328000"/> <node id="29012520" visible="true" version="2" changeset="3098893" timestamp="2009-11-12T15:12:59Z" user="Abuls" uid="14113" lat="56.7183050" lon="21.6051939"/> <node id="29012518" visible="true" version="2" changeset="3098893" timestamp="2009-11-12T15:12:59Z" user="Abuls" uid="14113" lat="56.7184563" lon="21.6161018"/> <node id="29012516" visible="true" version="2" changeset="3100827" timestamp="2009-11-12T19:23:00Z" user="Abuls" uid="14113" lat="56.7180402" lon="21.6222515"/> <node id="29012514" visible="true" version="2" changeset="3100827" timestamp="2009-11-12T19:23:00Z" user="Abuls" uid="14113" lat="56.7191410" lon="21.6324709"/> 

So I need to find in 2. txt all lines where nod id is equal with nummber given in 1. txt file and than I need to cut out the latitude and longitude values of this searched string line. 因此,我需要在2. txt中找到nod id等于1. txt文件中给出的编号的所有行,然后我需要切出此搜索字符串行的纬度和经度值。

Can anybody help me? 有谁能够帮助我?

I will give you a little code to get you started. 我将给您一些代码以帮助您入门。

// Step 1: Need to load the files:
// put the paths to your files in these two variables
$textFile = 'locations.txt';
$xmlFilePath = 'data.xml';

$idHandle = fopen($textFile, 'r');
$dom = new DOMDocument();
$dom->load($xmlFilePath);
$dom->preserveWhiteSpace = false;

$xpath = new DOMXPath($dom);

// Step 2: getting each line in the text file
while ($id = fgets($idHandle)) {
  $id = (int) $id;
  // Step 3: selecting all the nodes that have ids matching 
  // the id in the text file
  $query = "//node[@id={$id}]";
  $list = $xpath->evaluate($query);

  foreach ($list as $node) {
    echo "Node: {$id}, Latitude: " . $node->getAttribute('lat') 
      . ", " .  "Longitude: " . $node->getAttribute('lon') . "\n"; 
  }
}

I get the following output: 我得到以下输出:

Node: 29012520, Latitude: 56.7183050, Longitude: 21.6051939
Node: 29012516, Latitude: 56.7180402, Longitude: 21.6222515
Node: 29012514, Latitude: 56.7191410, Longitude: 21.6324709

Let me know if you need anything else. 需要帮助请叫我。

You could use a combination of SimpleXMLElement , foreach , file_get_contents , and preg_split to get the result you desire. 您可以结合使用SimpleXMLElementforeachfile_get_contentspreg_split获得所需的结果。 Here is what is meant: 这是什么意思:

    <?php
        // GET THE CONTENTS OF THE TEXT FILE CONTAINING IDS
        // AND BUNDLE IT INTO A VARIABLE FOR LATER USE.
        $txtFileContent = file_get_contents(__DIR__ . "/ids.txt");

        // CONVERT THE CONTENTS OF THE TEXT FILE TO AN ARRAY
        $arrTextData    = preg_split("#[\n\r]#", $txtFileContent);


        // CREATE A SIMPLE XML ELEMENT USING THE XML FILE.
        $sXML           = new SimpleXMLElement(__DIR__ . "/xml_file_name.xml", 0, true);

        // LOOP THROUGH ALL THE ELEMENTS IN THE CHILDREN LIST
        // AND TRY TO MATCH EACH ELEMENT WITH EACH KEY ON THE $arrTextData ARRAY.
        // THIS WOULD IMPLY A NESTED LOOP... ALSO BUILD AN ARRAY OF
        // MATCHED-ELEMENTS WITH THE UNIQUE ID AS THE KEY IN THE PROCESS.
        $arrMatchedElements = array();

        foreach($sXML->children() as $nodeKey=>$nodeData){
            /**@var SimpleXMLElement $nodeData */
            foreach($arrTextData as $iKey=>$ID){
                if($ID == $nodeData->attributes()->id){
                    $arrMatchedElements[$ID]    = $nodeData->attributes();
                }
            }
        }

        var_dump($arrMatchedElements);
        // THE var_dump(...) PRODUCES...            
        array (size=3)
          29012520 => 
            object(SimpleXMLElement)[6]
              public '@attributes' => 
                array (size=9)
                  'id' => string '29012520' (length=8)
                  'visible' => string 'true' (length=4)
                  'version' => string '2' (length=1)
                  'changeset' => string '3098893' (length=7)
                  'timestamp' => string '2009-11-12T15:12:59Z' (length=20)
                  'user' => string 'Abuls' (length=5)
                  'uid' => string '14113' (length=5)
                  'lat' => string '56.7183050' (length=10)
                  'lon' => string '21.6051939' (length=10)
          29012516 => 
            object(SimpleXMLElement)[5]
              public '@attributes' => 
                array (size=9)
                  'id' => string '29012516' (length=8)
                  'visible' => string 'true' (length=4)
                  'version' => string '2' (length=1)
                  'changeset' => string '3100827' (length=7)
                  'timestamp' => string '2009-11-12T19:23:00Z' (length=20)
                  'user' => string 'Abuls' (length=5)
                  'uid' => string '14113' (length=5)
                  'lat' => string '56.7180402' (length=10)
                  'lon' => string '21.6222515' (length=10)
          29012514 => 
            object(SimpleXMLElement)[8]
              public '@attributes' => 
                array (size=9)
                  'id' => string '29012514' (length=8)
                  'visible' => string 'true' (length=4)
                  'version' => string '2' (length=1)
                  'changeset' => string '3100827' (length=7)
                  'timestamp' => string '2009-11-12T19:23:00Z' (length=20)
                  'user' => string 'Abuls' (length=5)
                  'uid' => string '14113' (length=5)
                  'lat' => string '56.7191410' (length=10)
                  'lon' => string '21.6324709' (length=10)

You can also make this more Object Oriented like so: 您还可以像这样使它更面向对象:

    <?php   
        // GET THE CONTENTS OF THE TEXT FILE CONTAINING IDS
        // AND BUNDLE IT INTO A VARIABLE FOR LATER USE. 
        $txtFileContent = file_get_contents(__DIR__ . "/ids.txt");

        // CONVERT THE CONTENTS OF THE TEXT-FILE TO AN ARRAY
        $arrTextData    = preg_split("#[\n\r]#", $txtFileContent);

        // CREATE A SIMPLE XML ELEMENT USING THE XML FILE.
        $sXML           = new SimpleXMLElement(__DIR__ . "/xml_file_name.xml", 0, true);

        // LOOP THROUGH ALL THE ELEMENTS IN THE CHILDREN LIST
        // AND TRY TO MATCH EACH ELEMENT WITH EACH KEY ON THE $arrTextData ARRAY.
        // THIS WOULD IMPLY A NESTED LOOP... ALSO BUILD A MATCHED-ELEMENTS
        // ARRAY IN THE PROCESS.
        $arrMatchedElements = array();

        foreach($sXML->children() as $nodeKey=>$nodeData){
            /**@var SimpleXMLElement $nodeData */
            foreach($arrTextData as $iKey=>$ID){
                if($ID == $nodeData->attributes()->id){
                    $tempPropsObj               = new stdClass();
                    $tempPropsObj->id           = $nodeData->attributes()
                            ->id->__toString();
                    $tempPropsObj->lon          = $nodeData->attributes()->lon->__toString();
                    $tempPropsObj->lat          = $nodeData->attributes()->lon->__toString();
                    $tempPropsObj->uid          = $nodeData->attributes()->uid->__toString();
                    $tempPropsObj->user         = $nodeData->attributes()->user->__toString();
                    $tempPropsObj->timestamp    = $nodeData->attributes()->timestamp->__toString();
                    $tempPropsObj->changeset    = $nodeData->attributes()->changeset->__toString();
                    $tempPropsObj->version      = $nodeData->attributes()->version->__toString();
                    $tempPropsObj->visible      = $nodeData->attributes()->visible->__toString();
                    $arrMatchedElements[$ID]    = $tempPropsObj;
                }
            }
        }

        var_dump($arrMatchedElements);
        // DISPLAYS...
        array (size=3)
          29012520 => 
            object(stdClass)[6]
              public 'id' => string '29012520' (length=8)
              public 'lon' => string '21.6051939' (length=10)
              public 'lat' => string '21.6051939' (length=10)
              public 'uid' => string '14113' (length=5)
              public 'user' => string 'Abuls' (length=5)
              public 'timestamp' => string '2009-11-12T15:12:59Z' (length=20)
              public 'changeset' => string '3098893' (length=7)
              public 'version' => string '2' (length=1)
              public 'visible' => string 'true' (length=4)
          29012516 => 
            object(stdClass)[5]
              public 'id' => string '29012516' (length=8)
              public 'lon' => string '21.6222515' (length=10)
              public 'lat' => string '21.6222515' (length=10)
              public 'uid' => string '14113' (length=5)
              public 'user' => string 'Abuls' (length=5)
              public 'timestamp' => string '2009-11-12T19:23:00Z' (length=20)
              public 'changeset' => string '3100827' (length=7)
              public 'version' => string '2' (length=1)
              public 'visible' => string 'true' (length=4)
          29012514 => 
            object(stdClass)[8]
              public 'id' => string '29012514' (length=8)
              public 'lon' => string '21.6324709' (length=10)
              public 'lat' => string '21.6324709' (length=10)
              public 'uid' => string '14113' (length=5)
              public 'user' => string 'Abuls' (length=5)
              public 'timestamp' => string '2009-11-12T19:23:00Z' (length=20)
              public 'changeset' => string '3100827' (length=7)
              public 'version' => string '2' (length=1)
              public 'visible' => string 'true' (length=4)

Hope this helps a bit.... GOOD LUCK ;-) 希望这会有所帮助。

Okay first of all in your example your XML code has no ending tag </osm> , which probably was only a mistake when copy paste. 好的,首先在您的示例中,您的XML代码没有结束标记</osm> ,这可能只是复制粘贴时的一个错误。

Because you have an XML file, you don't need to parse it by yourself, PHP offers a lot of functions to do that for you. 因为您有一个XML文件,所以您无需自己解析它,PHP提供了许多功能来帮助您完成此任务。

As far as I know, there is no possibility to check if the value of a XML is equal to another value, so you have to check it in two loops, as you can see in my example below. 据我所知,不可能检查XML的值是否等于另一个值,因此您必须在两个循环中对其进行检查,如下面的示例所示。

<?php
//Read the id's
$ids = file("txt.txt", FILE_IGNORE_NEW_LINES);

//Read the XML file
$xmlContent = file_get_contents("txt.xml");

//Convert XML file to an object
$xmlObjects = simplexml_load_string($xmlContent);

foreach ($ids as $id) {
    foreach ($xmlObjects->node as $node) {

        //Check if id's are equal
        if ($node["id"] == $id) {
            echo "ID: ".$id;
            echo " Latitude: ".$node["lat"];
            echo " Longidtude ".$node["lon"];
            echo "<br>";
        }
    }
}

Output: 输出:

ID: 29012520 Latitude: 56.7183050 Longidtude 21.6051939
ID: 29012516 Latitude: 56.7180402 Longidtude 21.6222515
ID: 29012514 Latitude: 56.7191410 Longidtude 21.6324709

Try something like this. 尝试这样的事情。

$handle = fopen("1.txt", "r");

$xml = simplexml_load_file("2.xml") or die("Error: Cannot create object");

if ($handle) {

    while (($line = fgets($handle)) !== false) {

        foreach ($xml as $key => $value) {

            if ($value['id'] == trim($line)) {

                echo "id: " . $value['id'] . " Lat => " . $value['lat'] . " " . "lon => " . $value['lon'] . "</br>";
            }
        }
    }

    fclose($handle);

} else {
    // error opening the file.
} 

Output 输出量

id: 29012520 Lat => 56.7183050 lon => 21.6051939
id: 29012516 Lat => 56.7180402 lon => 21.6222515
id: 29012514 Lat => 56.7191410 lon => 21.6324709

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM