简体   繁体   中英

How to search for string in array in PHP?

so i got this big xml which can be found at here and i store in my database as settype-setId-partId and i want to filter unknown strings and replace them.Here's what i tried:

<?php
try {
    $conn = new PDO("mysql:host=localhost;dbname=db", "root", "");
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
$figuredata = simplexml_load_file("figuredata.xml");

$users = $conn->prepare("SELECT figure, username from players");
$users->execute();
$users = $users->fetchAll(PDO::FETCH_OBJ);

foreach($figuredata->sets->settype as $settype) {
    foreach($settype->set as $set) {
        foreach($set->part as $part) {
            foreach($users as $user ) {
                $lookArr = explode(".",$user->figure);
                foreach($lookArr as $look ){
                    $lookArrNew = explode("-", $look);
                    if($lookArrNew[1] != $set->attributes()->id && $lookArrNew[2] != $part->attributes()->id) {
                        echo "fail";
                    }

                }
            }   
        }
    }
}

But it returns fail for every string. What should I do?

If you use XPath to search for the data rather than having all of the various loops, you can reduce the code to reading in the players and then searching for the entry.

This uses an XPath expression //set[@id="'.$lookArr[1].'"]/part[@id="'.$lookArr[2].'"] , which will look for something like //set[@id="3774"]/part[@id="3329"] . This is a <set> value with an attribute value for id = 3774, which has a <part> with an id attribute of 3329.

xpath() returns a list, so if it's empty the value isn't found.

$users = $users->fetchAll(PDO::FETCH_OBJ);

foreach($users as $user ) {
    $lookArr = explode(".",$user->figure);
    foreach($lookArr as $look ){
        $lookArr = explode("-",$figure);
        $set = $figuredata->xpath('//set[@id="'.$lookArr[1].'"]/part[@id="'.$lookArr[2].'"]');
        if ( empty($set) )   {
            echo "fail";
        }
        else    {
            echo $set[0]->asXML();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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