从数组中检索值并设置条件


Retrieve a value from an array and make a condition

我在WordPress上使用了以下代码:

if($terms && !is_wp_error($terms) ) {
  $colors = array();
  foreach ($terms as $term) {
    $colors[] = '''' . $term->slug . '''';
  }
}
print_r(array_values($thePack));

变量$color现在是一个基本数组,print_r显示如下:

Array (
    [0] => 'white'
    [1] => 'green'
)

我想设置一个条件来识别数组是否有特定的值,例如:

if(in_array('white', $colors) {
  echo "This is white";
}

但是,它根本不起作用,因为in_array无法识别数组中的值!

我怎样才能使条件发挥作用?

您的数组值(颜色名称)包括单引号,在搜索值时需要包括这些引号:

if(in_array("'white'", $colors) {
    // ...
}

为什么不这样做:

while(list($key, $value) = each($array)){
    if($value == 'white'){
       echo 'this is white';
    }
}

问题是将颜色转义到数组中。而不是使用

$colors[] = ''''.$term->slug.''''

只做

$colors[] = $term->slug

当您将slug输出到网页或数据库时,您可以对其进行转义。