【问题标题】:Looping through an array and create from each key an HTML anchor in PHP循环遍历数组并从每个键创建 PHP 中的 HTML 锚点
【发布时间】:2015-03-01 07:32:10
【问题描述】:

PHP 新手,大学时我得到了一个基本任务的骨架:我必须创建一个包含 3 个人及其年龄的关联数组,然后我必须循环该数组 (foreach) 并为每把钥匙。每个锚点/链接都会影响 if (isset($_GET['name'])

这是关联数组($age)

$age['Atticus'] ="2100";
$age['McDunna'] ="96";
$age['Oberon']  ="13"; 

我可以在这个“循环”中更改/添加什么,以便它们影响 if (isset($_GET['name'])

foreach ($age as $key => $value) {
    echo "<a href=\"GET\">'$key'</a>";
            echo "<br>";  

我还考虑让数组从每个键创建一个表单,以便我可以使用 form method =get,但我不太确定这是否可行。

这是我的第一个问题,如果某些部分令人困惑,我很抱歉,我很乐意澄清一些事情。如果更容易,我可以提供骨架代码:

<?php

 // TODO make an assoc array with 3 people and their age.; 


if( isset( $_GET['name']) ){

// TODO create a text with the name and age; 
    $infoText= "$age";



$infoText =  NULL; 
}else{

// TODO create  generic text.; 

}
?>




<!DOCTYPE html>
<html>
 <head>

 </head>

<body>

    <header>
        <?php
            // TODO "Loop" the $age array. and  for every key  create an HTML anchor/link.;
        foreach ($age as $key => $value) {
                 echo "<a href=\"GET\">'$key'</a>";
                 echo "<br>";
        }

        ?>

    </header>

    <h3><?php // TODO display the infoText ?></h3>

</body>

【问题讨论】:

    标签: php arrays get skeleton-code


    【解决方案1】:

    替换这个:

    <?php
    
     // TODO make an assoc array with 3 people and their age.; 
    $age['Atticus'] = 2100;
    $age['McDunna'] = 96;
    $age['Oberon']  = 13; 
    $infoText = 'Not selected';
    if (isset( $_GET['name']) ){
        $name = $_GET['name'];
        if(array_key_exists($name, $age)) {
            $infoText = 'Name: ' .$name . ' Age: '. $age[$name]; // Name: John Age: 27
        }
    }
    ?>
    
    <!DOCTYPE html>
    <html>
     <head>
     </head>
    <body>
    
        <header>
            <?php
                // TODO "Loop" the $age array. and  for every key  create an HTML anchor/link.;
            foreach ($age as $key => $value) {
                     echo "<a href=\"?name=".$key."\">".$key."</a>";
                     echo "<br>";
            }
    
            ?>
    
        </header>
    
        <h3><?php echo $infoText; ?></h3>
    
    </body>
    

    【讨论】:

      猜你喜欢
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 2019-07-10
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多