我使用这个方法来检查检查了哪个term_id:
if ($type) {
if ($type[0]->term_id == 24) echo '<div class="one"></div>';
if ($type[1]->term_id == 23) echo '<div class="two"></div>';
if ($type[2]->term_id == 22) echo '<div class="three"></div>';
}
但问题是,只有当这三个都在数组中时,它才能工作。
如果我的数组中只有两个,term_id=24和term_id=22,那么它只找到24而没有找到22,因为现在22将是$type[1]而不是type[2]。
因此,我需要以某种方式放入一些通配符"*",以包括所有可能性,如if ($type[*]->term_id == 24) echo '<div class="one"></div>';
如何在php中使用最简单的方法?
if ($type) {
foreach($type as $element) {
switch($element->term_id) {
case 24: echo '<div class="one"></div>';
break;
case 23: echo '<div class="two"></div>';
break;
case 22: echo '<div class="three"></div>';
break;
}
}
}
if ( isset($type) && is_array($type) ) {
foreach($type as $element) {
switch($element->term_id) {
case 24:
echo '<div class="one"></div>';
break;
case 23:
echo '<div class="two"></div>';
break;
case 22:
echo '<div class="three"></div>';
break;
}
}
}
为您的选项定义一个Map,并遍历您的$type
-阵列:
$map = array(22=>'three',23=>'two',24=>'one');
if ($type){
array_walk(
$type,
function($item,$key,$map){
if(in_array($item->term_id, array_keys($map))){
echo '<div class="'.$map[$item->term_id].'"></div>';
}
},
$map
);
}
另一种方法是使用此函数
function in_array_field($needle, $needle_field, $haystack, $strict = false) {
if ($strict) {
foreach ($haystack as $item)
if (isset($item->$needle_field) && $item->$needle_field === $needle)
return true;
}
else {
foreach ($haystack as $item)
if (isset($item->$needle_field) && $item->$needle_field == $needle)
return true;
}
return false;
}
您将函数用作:
if ($type) {
if (in_array_field('24', 'term_id', $type))
echo '<div class="one"></div>';
if (in_array_field('23', 'term_id', $type))
echo '<div class="two"></div>';
if (in_array_field('22', 'term_id', $type))
echo '<div class="three"></div>';
}