[英]get key or value from array to use in php
我想將值從數組分配給一個簡單的變量,我的代碼如下:
$codeval = $_POST['code']; //can be Apple or Banana or Cat or Dog
$systemrefcode = array("a" => "Apple", "b" => "Banana", "C" => "Cat", "D" => "Dog");
foreach($systemrefcode as $code => $value) {
if($codeval == $value){ //if Apple exists in array then assign code and use it further
$codes = $code;//Assign code to codes to use in next step
}
$selection = 'Your Selection is -'.$codes.'and its good.';
echo $selection;
當我在控制台中簽入時,它沒有顯示任何響應。 我究竟做錯了什么?
您可以使用array_search()獲得所需值的鍵:
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
因此,對於您的代碼,您可以像這樣使用:
$codeval = $_POST['code'];
$systemrefcode = array("a" => "Apple", "b" => "Banana", "C" => "Cat", "D" => "Dog");
$code = array_search($codeval, $systemrefcode);
$selection = 'Your Selection is - '.$code.' and its good.';
echo $selection;
OBS:
您可以在有匹配項時break
foreach
,然后回顯字符串。
$post = "1-Apple";
$codeval = explode('-', $post)[1];
$systemrefcode = array("a" => "Apple", "b" => "Banana", "C" => "Cat", "D" => "Dog");
$codes = "";
foreach ($systemrefcode as $code => $value) {
if ($codeval === $value) { //if Apple exists in array then assign code and use it further
$codes = $code;//Assign code to codes to use in next step
break;
}
}
if ($codes !== "") {
$selection = 'Your Selection is -' . $codes . ' and its good.';
echo $selection; // Your Selection is -a and its good.
} else {
echo "codes is empty";
}
您可以翻轉$systemrefcode
數組,使值成為鍵,反之亦然。
$coderefsystem = array_flip($systemrefcode);
$codes = $coderefsystem($codeval);
$selection = 'Your Selection is -'.$codes.'and its good.';
echo $selection;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.