检查php数组的键/值重复项

时间:2014-08-18 16:30:29

标签: php arrays

我的数组是这样的:

   $sth = array(
        array("group" => "1", "name" => "John", "whatever" => "a"),
        array("group" => "1", "name" => "John", "whatever" => "b"), // this is the duplicate I want to remove
        array("group" => "1", "name" => "Henry", "whatever" => "c"),
        array("group" => "2", "name" => "John", "whatever" => "d"),
        array("group" => "2", "name" => "Peter", "whatever" => "e")
    )

我想删除重复的1/John条目,但不删除2/John条目,因为它不重复。我只想检查这两个值,而不是"无论什么"价值,因为那总是不同的。我知道我可以使用in_array来搜索"John",或array_search来检查密钥,但密钥并不总是与名称相关联,所以我只需要删除key/value完全相同的重复项。我想的是:

$cleaned_sth = array();
foreach($sth as $s) {
    $group = $s[0];
    $name = $s[1];
    if( in_array($group => $name, $cleaned_sth ) continue;
    else $cleaned_sth[] = array("group" => $group, "name" => $name);
}

1 个答案:

答案 0 :(得分:-1)

这是一个伪代码(因为我现在很长时间没有用PHP编程)。

define an empty map
foreach(entry in array) map[entry["group"] + entry["name"]] = entry
map.values