基于一堆变量在PHP中创建一个目录


Creating a directory in PHP based on a bunch of variables

我一直在尝试创建一个遵循特定结构的目录,但似乎什么都没有发生。我通过如下定义多个变量来解决这个问题:

 $rid = '/appicons/';
 $sid = '$artistid';
 $ssid = '$appid';
 $s = '/';

我一直在使用的功能就是这样运行的:

 $directory = $appid;
 if (!is_dir ($directory)) 
    { 
     mkdir($directory); 
    }

这很管用。但是,我希望在创建的目录中具有以下结构:/appicons/$artistid/$appid/

然而,似乎什么都不起作用。我知道,如果我要在$directory中添加更多的变量,那么我必须在它们周围使用引号并将它们连接起来(这会让人感到困惑)。

有人有什么解决方案吗?

$directory = "/appicons/$artistid/$appid/";
if (!is_dir ($directory)) 
{
     //file mode
     $mode = 0777;
     //the third parameter set to true allows the creation of 
     //nested directories specified in the pathname.
     mkdir($directory, $mode, true);
}

这应该可以实现您想要的:

$rid = '/appicons/';
$sid = $artistid;
$ssid = $appid;
$s = '/';
$directory = $rid . $artistid . '/' . $appid . $s;
if (!is_dir ($directory)) { 
    mkdir($directory); 
}

当前代码不起作用的原因是您试图在字符串文本中使用变量。PHP中的字符串文字是用单引号(')括起来的字符串。该字符串中的每个字符都被视为一个字符,因此任何变量都将被解析为文本。取消引用变量,使您的声明看起来像以下修复了您的问题:

$rid = '/appicons/';
$sid = $artistid;
$ssid = $appid;
$s = '/';

下一行将您的变量连接到一个路径中:

$directory = $rid . $artistid . '/' . $appid . $s;

连接的工作原理与此类似

$directory = $rid.$artistid."/".$appid."/"

当您将一个变量分配给另一个变量时,不需要在它周围加引号,因此您应该寻找以下内容。

$rid = 'appicons';
$sid = $artistid;
$ssid = $appid;

然后。。。

$dir = '/' . $rid . '/' . $sid . '/' . $ssid . '/';
if (!is_dir($dir)) { 
  mkdir($dir); 
}