如何从其他文件调用数组

时间:2015-10-29 08:22:55

标签: php arrays

我有一个来自oher文件php的数组,并在select data html中显示

这是我的数组

array.php

<?php
    $category_attachment = array(       "SPK" ,    
                                        "Justifikasi" ,  
                                        "PR" ,  
                                        "RAB" ,  
                                        "Proc" ,  
                                        "PO" ,  
                                        "Notulen" ,  
                                        "Sertifikat" ,  
                                        "BAUT" ,  
                                        "BAST" ,  
                                        "Tagihan" ,
                                        "Other"
                                ); ?>

myfile.php

<?php include "array.php" ?>

<select name="category" id="category">
<option value="">Choose Category</option>
  // I want array data in here
</select>

帮我谢谢

5 个答案:

答案 0 :(得分:1)

只需在print_r($category_attachment);中尝试myfile.php,看看会发生什么。您可以在包含文件

后访问该变量

此外,您应该使用disabled属性禁用第一个选项;)

<?php 
    include "array.php" 
    print_r($category_attacment);
?>

<select name="category" id="category">
    <option disabled>Choose Category</option>
<?php
foreach($category_attachment as $cat) { 
    echo "<option value='" . $cat . "'>" . $cat . "</option>";
}
?>
</select>

这个例子不起作用:

<?php 
    print_r($category_attacment);
    include "array.php" 
?>

您必须先包含该文件,然后才能访问该变量。

答案 1 :(得分:1)

试试这个

<select name="category" id="category">
    <option value="">Choose Category</option>
    <?php
    foreach ($category_attachment as $value) {
        ?>
        <option value="<?php echo $value ?>"><?php echo $value ?></option>
        <?php
    }
    ?>
</select>

答案 2 :(得分:1)

您可以执行以下操作:

<select name="category" id="category">
<option value="">Choose Category</option>
    <?php
      foreach($category_attachment as $category){
      echo '<option value="'.$category'">'.$category.'</option>'; 
     }
     ?>
</select>

看看foreach doc,这在使用数组时非常有用:

http://php.net/manual/en/control-structures.foreach.php

答案 3 :(得分:1)

你可以这样做:

<?php include "array.php" ?>
<select name="category" id="category">
    <option value="">Choose Category</option>
    <?php foreach ($category_attachment as $category) {?>
        <option value="<?php echo $category; ?>"><?php echo $category; ?></option>  
    <?php } ?>
</select>

答案 4 :(得分:1)

就这么简单,

<select name="category" id="category">
    <?php
    foreach ($category_attachment as $value) {
        ?>
        <option value="<?= $value ?>"><?= $value ?></option>
        <?php
    }
    ?>
</select>