2014-12-07 35 views
0

我使用我的简单的项目,从另一个PHP文件获取变量名称。有些变量具有相同的价值..PHP的 - foreach跳过,如果结果是相同的值

我用的foreach显示在特定目录不同的PHP文件变量..

(1st app_config.php) $app_name = "Pass Generator"; 
(2nd app_config.php) $app_name = "Random Name Generator"; 
(3rd app_config.php) $app_name = "Love Meter"; 
(4th app_config.php) $app_name = "Random Name Generator"; 
(5th app_config.php) $app_name = "Lucky Number Generator"; 

由于我的第2和$ APP_NAME的第四变量相同的值,我怎么能跳过其中之一。因此,输出将是:

Pass Generator 
Random Name Generator 
Love Meter 
Lucky Number Generator 

这是我的代码:

$path = '../../apps/' . $name[0]; 
$results = scandir($path); 

foreach ($results as $result) { 
    if ($result === '.' or $result === '..') continue; 

    if (is_dir($path . '/' . $result)) { 
     require_once("../../apps/".$result."/app_config.php"); 
     $app .= $app_name."<Br>"; 
    } 
} 
echo $app_name; 

有人吗?由于

+1

我建议你HTTP: // foreach循环之前的//php.net/manual/en/function.array-unique.php(ps:foreach比while慢)。 – HellBaby 2014-12-07 04:06:20

回答

1
$path = '../../apps/' . $name[0]; 
$results = scandir($path); 

$arrProcessed = array(); 
foreach ($results as $result) { 
    if ($result === '.' or $result === '..' or array_key_exists($result, $arrProcessed)) continue; 
    $arrProcessed[$result] = true; 

    if (is_dir($path . '/' . $result)) { 
     require_once("../../apps/".$result."/app_config.php"); 
     $app .= $app_name."<Br>"; 
    } 
} 
echo $app_name; 
+1

可能想用isset代替。请参阅http://stackoverflow.com/a/9522522/627473 – 2014-12-07 04:00:11

+0

它只显示一个项目/元素。 :/ – user3232086 2014-12-07 04:00:14

1

作为替代方案,你可以收集他们一个数组内,然后破灭/与换行符胶水他们:

$path = '../../apps/' . $name[0]; 
$results = scandir($path); 

$apps = array(); 
foreach ($results as $result) { 
    if ($result === '.' or $result === '..') continue; 

    if (is_dir($path . '/' . $result)) { 
     require_once("../../apps/".$result."/app_config.php"); 
     $apps[$app_name] = null; 
    } 
} 

echo implode('<br/>', array_keys($apps)); 

或者另一种变化:

if (is_dir($path . '/' . $result)) { 
     require_once("../../apps/".$result."/app_config.php"); 
     $apps[] = $app_name; 
    } 
} 

echo implode('<br/>', array_unique($apps)); 
+0

'
',而不是'
':-) – Sebas 2014-12-07 04:04:53

+1

@Sebas都可以工作,有或没有自动关闭。即时通讯只是习惯它:) – Ghost 2014-12-07 04:07:29

+0

根据XML标准,它将是
而不是
因为它需要一个结束标签。但是一个被熏制的smartass决定在html 5中转储结束标记(你的
不会在html 4中验证,并且从我看到的没有那么多浏览器为5中引入的东西提供支持) – HellBaby 2014-12-07 04:10:44