有两个数组array_unique [英] array_unique with two arrays

查看:85
本文介绍了有两个数组array_unique的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有相同长度的两个数组($ SEARCH_TYPE,$ SEARCH_TERM)。我想删除在具有相同类型和搜索词(即 $ SEARCH_TYPE [$一] == $ SEARCH_TYPE [$ B&放有被搜索的意义上的重复;&安培; $ SEARCH_TERM [ $ A] == $ SEARCH_TERM [$ b] )。

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 search term (ie $search_type[$a] == $search_type[$b] && $search_term[$a] == $search_term[$b]).

我知道,我可以写这个使用循环,在想,如果有,它利用优势的简单(但同样有效)的方式内置函数?

I'm aware that I could write this using loops, was wondering if there's a simpler (but equally efficient) way that takes advantage of built in functions?

推荐答案

它看起来并不像有只使用内置功能来解决这个问题的简单方法。

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);

编辑:这是一个短,presumably更高效的之一,你最终有一个不太pretty数组:

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)
//                      );

这篇关于有两个数组array_unique的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆