简体   繁体   English

如何在 PHP 的数组中搜索字符串?

[英]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:所以我得到了这个大的 xml,可以在这里找到,我将其存储在我的数据库中作为settype-setId-partId ,我想过滤未知字符串并替换它们。这是我尝试过的:

<?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.如果您使用 XPath 来搜索数据而不是使用所有各种循环,则可以将代码减少为读取播放器,然后搜索条目。

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"] .这使用了 XPath 表达式//set[@id="'.$lookArr[1].'"]/part[@id="'.$lookArr[2].'"] ,它将寻找类似//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.这是一个<set>值,其属性值为 id = 3774,其中一个<part>的 id 属性为 3329。

xpath() returns a list, so if it's empty the value isn't found. xpath()返回一个列表,因此如果它为空,则找不到该值。

$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();
        }
    }
}

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

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