PHP - foreach通过迭代重复值

时间:2013-11-17 10:09:57

标签: php foreach duplicates laravel-4

我目前正在建立一个Laravel主题管理器并且我有点卡住了。

所以我有一个themes文件夹,其中包含实际主题文件的其他文件夹,这些文件夹还包含template.php,包含基本数据的文件夹nametitledescriptionversionauthor

如果实际主题在数据库中存在,则创建一个检查匹配的函数,如果是,则忽略读取template.php,如果没有读取该实际主题的文件夹并将文件内容存储在数据库中安装。

一切正常,如果数据库中只存储了一个主题详细信息,如果我安装了第二个,则会返回位于theme文件夹中的所有主题,如果存储的数据不止于此,则检查并查看数据库,它复制结果。

代码

protected $theme_path = 'app/themes';

protected $manifest = 'template.php';

public function notInstalledThemes()
{
    $themes = $this->all();

    // get all directories form theme folder 
    $directories = File::directories($this->theme_path);

    // replace back slash to forward slash
    $directories = str_replace('\\', '/', $directories);

    foreach ($themes as $theme) 
    {

        foreach ($directories as $directory) 
        {
            // we dont need the admin
            // and ignor the themes already installed
            if ($directory != $this->theme_path.'/admin' && $directory != $this->theme_path.'/'.$theme->name)
            {
                $notINstalled = File::getRequire($directory.'/'.$this->manifest);

                $data[] = $notINstalled;
            } 

        }

    }

    if (!empty($data)) return $data;
}

所以,如果我只有一个主题存储在数据库i和var_dump中,那么我的第二个foreach中的结果都很好

一个数据

 foreach ($directories as $directory) 
    {
        var_dump($directory);
        // we dont need the admin
        // and ignor the themes already installed
        if ($directory != $this->theme_path.'/admin' && $directory != $this->theme_path.'/'.$theme->name)
        {
            $notINstalled = File::getRequire($directory.'/'.$this->manifest);

            $data[] = $notINstalled;
        } 

}

输出

string(16) "app/themes/admin"
string(17) "app/themes/cosmos"
string(18) "app/themes/default"

我恢复了目录,

但如果另一个主题数据存储在数据库中,则迭代会复制结果

第二次出局

string(16) "app/themes/admin"
string(17) "app/themes/cosmos"
string(18) "app/themes/default"
string(16) "app/themes/admin"
string(17) "app/themes/cosmos"
string(18) "app/themes/default"

搜索网络,找到array_unique

但是没有真正奏效,有人可以给我一个如何避免这种情况的暗示吗?

1 个答案:

答案 0 :(得分:1)

如果数据库中有两个主题,则代码执行以下操作:

$themes = $this->all();
// Assuming you have admin and cosmos in your db:
// $themes = ['admin', 'cosmos']

$directories = File::directories($this->theme_path);
// $directories = ['admin', 'cosmos', 'default']

所以,循环运行如下:

foreach ($themes as $theme) 
{
    // 2 iterations: 'admin' and 'cosmos'
    foreach ($directories as $directory) 
    {
        // 3 iterations: 'admin', 'cosmos', and 'default'

这就是您所拥有的输出(2x3次迭代)的原因。

为了在$data数组中包含唯一条目,剩下的部分类似于以下内容,它使用PHP in_array函数。

if ($directory != $this->theme_path.'/admin' && $directory != $this->theme_path.'/'.$theme->name)
{
    $notINstalled = File::getRequire($directory.'/'.$this->manifest);

    if ( ! in_array($notInstalled, $data))
    {
        $data[] = $notINstalled;
    }
}