Foreach 回显数组 php 中元素的名称

Foreach echo out name of element in array php

我有一个 PHP 数组,看起来像这样

$melee = array(  
    "ct-knife" => "link",  
    "t-knife" => "link",  
    "zeus" => "link"  
);

foreach ($pistol as $value){
    echo '<option value="'.$value.'">"'.$value.'"</option>';
}

我希望我的 "Foreach" 打印出链接的名称,但它打印出了链接。 有谁知道如何解决这个问题?

提前致谢

对于关联数组,请更改您的 foreach 以使用键。以下内容将满足您的需求。

$melee = array(  
    "ct-knife" => "link",  
    "t-knife" => "link",  
    "zeus" => "link"  
);

foreach ($pistol as $key => $value){
    echo '<option value="'.$key.'">"'.$key.'"</option>';
}

这是另一种方式:

<?php
/**
* Created by PhpStorm.
* User: jokuf
* Date: 7/19/15
* Time: 8:34 PM
*/
$melee = array(
"ct-knife" => "link",
"t-knife" => "link",
"zeus" => "link"
);

function selectWeapon($melee){
$i = 0;
echo '<select>';


while ($i < count($melee)) {
    foreach ($melee AS $key => $value) {
        echo '<option>' . $key . '</option>';
        $i++;
    }
}
echo '</select>';
}

selectWeapon($melee);