繁体   English   中英

PHP(如果在数组中)使用值

[英]PHP if in array, do something with the value

我正在尝试检查值是否在数组中。 如果是这样,请获取该数组值并对其进行处理。 怎么做?

这是我要执行的操作的一个示例:

$the_array = array("buejcxut->10", "jueofi31->20", "nay17dtt->30");

if (in_array('20', $the_array)) {

    // If found, assign this value to a string, like $found = 'jueofi31->20'

    $found_parts = explode('->', $found);

    echo $found_parts['0']; // This would echo "jueofi31"    

}

应该这样做:

foreach($the_array as $key => $value) {
    if(preg_match("#20#", $value)) {
        $found_parts = explode('->', $value);
    }
    echo $found_parts[0];
}

并用您想要的任何值替换“ 20”。

您最好在foreach循环中检查它:

foreach ($the_array as $key => $value) {
  if ($value == 20) {
    // do something
  }
  if ($value == 30) {
    //do something else
  }
}

您对数组的定义也很奇怪,您是否想拥有:

$the_array = array("buejcxut"=>10, "jueofi31"=>20, "nay17dtt"=>30);

使用$ key上方的数组是元素键(buejcxut,jueofi31等),而$ value是该元素的值(10、20等)。

这是一个如何使用正则表达式搜索数组值的示例。

<?php

$the_array = array("buejcxut->10", "jueofi31->20", "nay17dtt->30");

$items = preg_grep('/20$/', $the_array);

if( isset($items[1]) ) {

    // If found, assign this value to a string, like $found = 'jueofi31->20'

    $found_parts = explode('->', $items[1]);

    echo $found_parts['0']; // This would echo "jueofi31"    

}

您可以在此处查看演示: http : //codepad.org/XClsw0UI

如果要定义索引数组,则应如下所示:

$my_array = array("buejcxut"=>10, "jueofi31"=>20, "nay17dtt"=>30);

那么你可以使用in_array

if (in_array("10", $my_array)) {
    echo "10 is in the array"; 
    // do something
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM