array_unique with two arrays

前端 未结 3 1524
耶瑟儿~
耶瑟儿~ 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:46

    It doesn't look like there's a simple way to solve the problem using just built-in functions.

    This (at least logically) should work.

    $search_terms = array('a', 'b', 'c', 'c', 'd', 'd');
    $search_types = array( 1,   2,   3,   4,   5,   5);
    
    $terms = array_fill_keys($search_terms, array());
    // Loop through them once and make an array of types for each term
    foreach ($search_terms as $i => $term)
        $terms[$term][] = $search_types[$i];
    
    // Now we have $terms = array('a' => array(1),
    //                            'b' => array(2),
    //                            'c' => array(3, 4),
    //                            'd' => array(5, 5)
    //                      );
    
    // Now run through the array again and get rid of duplicates.
    foreach ($terms as $i => $types)
        $terms[$i] = array_unique($types);
    

    Edit: Here's a shorter and presumably more efficient one where you end up with a less pretty array:

    $search_terms = array('a', 'b', 'c', 'c', 'd', 'd');
    $search_types = array( 1,   2,   3,   4,   5,   5);
    
    $terms = array_fill_keys($search_terms, array());
    // Loop through them once and make an array of types for each term
    foreach ($search_terms as $i => $term)
        $terms[$term][$search_types[$i]] = 1;
    
    // Now we have $terms = array('a' => array(1 => 1),
    //                            'b' => array(2 => 1),
    //                            'c' => array(3 => 1, 4 => 1),
    //                            'd' => array(5 => 1)
    //                      );
    

提交回复
热议问题