Foreach回显出数组php中的元素名称[关闭]
问题描述:
I have a PHP array, that look like this
$melee = array(
"ct-knife" => "link",
"t-knife" => "link",
"zeus" => "link"
);
foreach ($pistol as $value){
echo '<option value="'.$value.'">"'.$value.'"</option>';
}
and I want my "Foreach" to print out the names of the links, but it prints out the links. Does anyone know how to fix this?
Thanks in advance
答
For associative arrays alter your foreach to use the keys. The following will get you what you want.
$melee = array(
"ct-knife" => "link",
"t-knife" => "link",
"zeus" => "link"
);
foreach ($pistol as $key => $value){
echo '<option value="'.$key.'">"'.$key.'"</option>';
}
答
This is another way :
<?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);