Using array_search for multi value search

前端 未结 3 2010
日久生厌
日久生厌 2021-01-25 07:48
  $array_subjected_to_search =array(
  array(
          \'name\' => \'flash\',
          \'type\' => \'hero\'
      ),

  array(
          \'name\' => \'zoom\',         


        
3条回答
  •  滥情空心
    2021-01-25 08:13

    I think I would just make my own function using a loop that will just retrieve the array I want based on either one or two parameters.

    function getValueMatch($array, $val1, $val2 = false, $type = 'name')
        {
            foreach($array as $key => $row) {
                # See note below, but it might be handy to have a reversible key name
                if($row[$type] == $val1) {
                    if($val2) {
                        # You can put a changeable key name to reverse-find
                        # It might be helpful to search for the other key first
                        # at some point, best to keep your options open!
                        $altVar = ($type == 'name')? 'type' : 'name';
                        if($row[$altVar] == $val2)
                            return $row;
                    }
                    else
                        return $row;
                }
            }
        }
    
    $array =array(
      array(
              'name' => 'flash',
              'type' => 'hero'
          ),
    
      array(
              'name' => 'zoom',
              'type' => 'villian'
          ),
    
      array(
              'name' => 'snart',
              'type' => 'antihero'
          ),
      array(
            'name' => 'flash',
            'type' => 'camera'
          )
      );
    
    print_r(getValueMatch($array,'flash','camera'));
    

    Gives you:

    Array
    (
        [name] => flash
        [type] => camera
    )
    

    Example of reverse match (type instead of name):

    print_r(getValueMatch($array,'antihero',false,'type'));
    

    Gives you:

    Array
    (
        [name] => snart
        [type] => antihero
    )
    

提交回复
热议问题