-1

我有一组人在 html 文件中在线注册。我正在使用它,以便每个人都可以分配给他们一个图像。但是当检查 using name 是否已在使用时,in_array 函数返回 false 并允许脚本继续。

$user = "< img src='default.jpg' />John";
$explode = array("<img src='tress.jpg' />John");

if(in_array($user, $explode))
   {
   //show login script if user exists
   }
   else
    {
     //continue to script
     }

现在这不起作用的原因是数组中的 john 与 $user 中的 john 不同。无论如何检查名称是否存在于数组中?回复时请说明。

4

1 回答 1

4

与其问“我该如何解决这个问题?”,不如先问“我为什么会遇到这个问题?”

$user = "< img src='default.jpg' />John";

< img src='default.jpg' />John用户名吗?你为什么用它作为一个?我猜这背后有一些聪明的想法,比如“好吧,我总是用他们的名字来显示用户的图片,所以我只会让图片成为他们名字的一部分这会导致比它解决的问题更多的问题。这回到计算机科学中一个叫做关注点分离的大概念。图像在逻辑上不是用户名的一部分,所以不要将它存储为一个。如果你总是一起显示它们,你可以使用函数来显示用户的以标准方式获取信息,而无需将图像作为用户名的一部分。

所以首先,从名称中删除图像。有几种方法可以单独存储它。

我建议使用一个类

class User {
    public $name;
    public $imageSource;

    // The following functions are optional, but show how a class
    // can be useful.

    /**
     * Create a user with the given name and URL to their image
     */
    function __construct($name, $imageSource) {
        $this->name = $name;
        $this->imageSource = $imageSource;
    }

    /**
     * Gets the HTML to display a user's image
     */
    function image() {
        return "<img src='". $this->imageSource ."' />";
    }

    /**
     * Gets HTML to display to identify a user (including image)
     */
    function display() {
        return $this->image() . $this->name;
    }
}

$user = new User("john", "default.jpg");

// or without the constructor defined
//$user = new User();
//$user->name = "john";
//$user->imageSource = "default.jpg";

echo $user->display();

如果你想更懒一点,你可以使用“数组”,但我不建议在一般情况下使用它,因为你失去了类的酷特性(比如那些函数):

$user = array(
   name => "john",
   image => "<img src='default.jpg' />";
);

echo $user["image"] . $user["name"];

在您的数据库中(如果您使用的是一个),将它们分开列,然后使用上述数据结构之一。

现在你有了这个,很容易使用foreach 循环查看用户名是否在给定列表中:

function userNameInList($user, $users) {
    for($users as $current) {
        if($user->name == $current) {
            return true;
        } 
    }
    return false;
}

$newUser = new User("John", "john.jpg");
$currentUsers = array("John", "Mary", "Bob");
if(userNameInList($newUser, $currentUsers) {
    echo "Sorry, user name " . $newUser->name . " is already in use!";
}

如果您是 PHP 新手,正常for循环可能更容易理解:

function userNameInList($user, $users) {
    for($i = 0; $i < count($users); ++i) {
        $current = $users[$i];
        if($user->name == $current) {
            return true;
        } 
    }
    return false;
}

让我知道如果其中任何一个不运行,我不再经常编写 PHP 了..

于 2012-10-19T20:52:55.510 回答