array_unique with two arrays

前端 未结 3 1565
耶瑟儿~
耶瑟儿~ 2021-01-27 07:04

I have two arrays of the same length ($search_type, $search_term). I want to remove any duplicates in the sense of there being searches that have the same type and

3条回答
  •  难免孤独
    2021-01-27 07:57

    Ok, here's an overly complex ad-hoc function foo() (lacking error handling, documentation and testing) that combines those two arrays. array_unique() takes care of the duplicates.

    'termC', 'bar'=>'termD', 'termB', 'termA');
    $search_type= array('typeA', 'typeB', 'foo'=>'typeC', 'bar'=>'typeD', 'typeB', 'typeA');
    
    $x = foo(array('term', $search_term), array('type', $search_type));
    $x = array_unique($x, SORT_REGULAR);
    var_dump($x);
    
    function foo() {
      $rv = array();
      $params = func_get_args();
      foreach ( array_keys($params[0][1]) as $key ) {
        $rv[$key] = array();  
        foreach( $params as $p ) {
          $rv[$key][$p[0]] = $p[1][$key];  
        }
      }
      return $rv;
    }
    

    prints

    array(4) {
      [0]=>
      array(2) {
        ["term"]=>
        string(5) "termA"
        ["type"]=>
        string(5) "typeA"
      }
      [1]=>
      array(2) {
        ["term"]=>
        string(5) "termB"
        ["type"]=>
        string(5) "typeB"
      }
      ["foo"]=>
      array(2) {
        ["term"]=>
        string(5) "termC"
        ["type"]=>
        string(5) "typeC"
      }
      ["bar"]=>
      array(2) {
        ["term"]=>
        string(5) "termD"
        ["type"]=>
        string(5) "typeD"
      }
    }
    

提交回复
热议问题