2015-06-03 33 views
0

我想爲一個大約20個元素的軟數據庫使用PHP包含文件。實際的數據將從RRD文件中收集,因此我不希望只使用20個元素的MySQL。爲元素的文件fruits.php我想是這樣的:PHP文件作爲軟數據庫?

<?php 
$fruit="Apple"; $colour="red"; 
$fruit="Banana"; $colour="yellow"; 
$fruit="Pear"; $colour="green"; 
?> 

在我的召回文件,results.php,我currenlty有以下代碼召回從fruits.php文件中的信息:

<?php 
include 'fruits.php'; 
$num=count($fruit); 
$i = 0; 
while ($i < $num){ 
echo "<p>My ".$fruit." is ".$colour.".</p>"; 
$i++; 
} 
?> 

因爲我不是一個適當的scriptor /程序員,我很盲目什麼應該是不同的,愚蠢的正確編碼。我也嘗試了一些其他方法,其中包括:

$num=glob($fruit); 

任何與此協助將非常感激。只是爲了確認,我想這個代碼的輸出是:

My Apple is red. 
My Banana is yellow. 
My Pear is green. 
+0

查找** **陣列中php http://php.net/manual/en/language.types.array.php –

+0

考慮使用序列化而不是將數組存儲爲PHP文件。特別是如果fruit.php中的數據被應用程序改變了。 – EJTH

+0

@Dagon下面的解決方案效果很好,但我仍然會遵循您的鏈接,這將有利於我的知識,謝謝! – JanBal

回答

0
你的情況

,變量$水果的值都將「鴨梨」,和$顏色=「綠色」 因爲你總是重新定義

<?php 
$fruits = array(); 
$fruits[] = ["name" => "Apple", "colour"=>"red"]; 
$fruits[] = ["name" => "Banana", "colour"=>"yellow"]; 
$fruits[] = ["name" => "Pear", "colour"=>"green"]; 
?> 

1路:

<?php 
include 'fruits.php'; 
$num=count($fruits); 
$i = 0; 
while ($i < $num){ 
echo "<p>My ".$fruits[$i]["name"]." is ".$fruits[$i]["colour"].".</p>"; 
$i++; 
} 
?> 

第二路(much easier):

<?php 
include 'fruits.php'; 
foreach ($fruits as $fruit){ 
    echo "<p>My ".$fruit["name"]." is ".$fruit["colour"].".</p>"; 
} 

?> 

其中$果實是數組$水果的元素

+0

第二種更簡單的方法在我的實際頁面中完美工作。非常感謝你!! – JanBal

+0

不客氣! – esperant

0

你fruits.php文件應包含可能的關聯數組,如:

<?php 
    $fruits = Array(
     Array('fruit' => 'Apple', 'color' => 'red'), 
     Array('fruit' => 'Banana', 'color' => 'yellow'), 
     // etc... 
    ); 
?> 

然後你訪問它在你的代碼一樣

<?php 
    echo "<p>My ".$fruits[$i]['fruit']." is ".$fruits[$i]['color'].".</p>"; 
?>