drvc63490
drvc63490
2015-06-03 08:32
浏览 26
已采纳

PHP文件为软DB?

I want to use a PHP include file for a soft DB of about 20 elements. The actual data will be collected from RRD files and thus I prefer not to use MySQL just for 20 elements. The file fruits.php for the elements I'm trying something like:

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

In my recall file, results.php, I currenlty have the following code to recall the information from the fruits.php file:

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

Since I'm not a proper scriptor/programmer, I'm quite blind to what should be different and stupid to proper coding. I have tried some other methods as well, one included:

$num=glob($fruit);

Any assistance with this will be really appreciated. Just to confirm the output I'd like for this code is to be:

My Apple is red.
My Banana is yellow.
My Pear is green.
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douzongmu2543
    douzongmu2543 2015-06-03 08:46
    已采纳

    in your case, variable $fruit will have a value "pear", and $colour = "green" Because you always redefine it

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

    1st way:

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

    2nd way (much easier):

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

    where $fruit is element of the array $fruits

    点赞 评论
  • dtoka218420
    dtoka218420 2015-06-03 08:43

    Your fruits.php file should probably contain an associative array, like:

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

    Then you'd access it in your code like

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

相关推荐