从数组中获取键或值以在php中使用

时间:2018-08-30 18:19:10

标签: php arrays foreach

我想将数组中的值分配给一个简单变量,我的代码如下:

$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;

当我在控制台中签入时,它没有显示任何响应。我在做什么错了?

3 个答案:

答案 0 :(得分:1)

您可以使用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。

    如果找不到值,
  1. array_search()将返回 false
  2. array_search()是区分大小写的,因此,如果数组中有“ Apple ”并搜索“ apple < / em>”,则返回 false

答案 1 :(得分:0)

如果存在匹配项,您可以从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";
}

答案 2 :(得分:0)

您可以翻转using (var handleProvider = new GCHandleProvider(myList)) { var b = EnumChildWindows(hwndParent, CallBack, handleProvider.Pointer); } 数组,使值成为键,反之亦然。

$systemrefcode