douyi6818 2018-05-21 10:40
浏览 71

检查数组中的值是否在其他数组中

I'm working on a filter for a wordpress page and I'm having trouble when trying to use multiple values.

The idea is to use a boolean to show or not show an item. Each item uses ACF to get various fields, in this case is color.

    if( isset($colores) ){
        foreach($colores as $color){
            if( in_array ( $color, get_field( 'color', get_the_ID() ) ) ){//Matches the filter
                $pasaColor = true;              
            }else if($color == null){//Not specified in the filter
                $pasaColor= true;               
            }else{//doesn't match the filter
                $pasaColor= false;              
            }
        }
    }  

This works if $colores has only one element, like this:

(
    [0] => yellow        
)

I compare it with the values of each item:

(
    [0] => yellow        
    [1] => red
    [2] => blue
)

This result in: $pasaColor=true

(          
    [1] => red
    [2] => blue
)

This one results in : $pasaColor=false

But if the filter gives more than one element only the last one stays true.

Filter:

(
    [0] => yellow        
    [1] => azul
)

Item1:

    (
    [0] => yellow        
    [1] => red
    [2] => pink
)

This results in $pasaColor=false

Item2:

(
    [0] => blue
    [1] => red
    [2] => pink
)

This results in $pasaColor=true

In item1 the result I'm getting means that the value "yellow" cannot be found in an array that actually contains the value "yellow".

And while we are at it, is there a simpler way to do this?

  • 写回答

1条回答 默认 最新

  • dsjhejw3232 2018-05-21 11:08
    关注

    I found the problem. At each cicle on the foreach my boolean would be overwritten so in the end is is like only the last element was checked.

    I added another boolean to prevent this.

    if( isset($colores) ){
        foreach($colores as $color){
            if( in_array ( $color, get_field( 'color', get_the_ID() ) ) ){//Matches the filter
                $pasaColor = true;    
                $itempasa = true;
            }else if($color == null){//Not specified in the filter
                $pasaColor= true;     
                $itempasa = true;                  
            }else if($itempasa==false){//doesn't match the filter
                $pasaColor= false;   
                $itempasa = false;           
            }
        }
    }  
    

    As I said before if anyone know of a better way of dealing with this please share, I would really appreciate it.

    评论

报告相同问题?

悬赏问题

  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效