检查数组中的相同值

时间:2018-05-07 19:11:31

标签: php arrays laravel

我有以下数组:

$teams = [["id" => 1, "address" => "A1"],["id" => 2, "address" => "A1"],["id" => 3, "address" => "A2"]];

如何检查并获得具有相同地址的团队?我的输出应该是团队ID 1和2?考虑到我不能使用硬编码地址。数据是动态的,来自数据库。

在php中,laravel。

提前谢谢!

3 个答案:

答案 0 :(得分:3)

首先,您需要按address进行分组,然后您可以使用array_filter()根据条件截断数组:

<?php
$teams = [["id" => 1, "address" => "A1"],["id" => 2, "address" => "A1"],["id" => 3, "address" => "A2"]];

// Set a new array
$filtered = [];

// Loop the teams
foreach($teams as $v)
{
    // Group the teams into their respective addresses
    $filtered[$v['address']][] = $v;
}

// Filter out any address with 1 or fewer teams
$filtered = array_filter($filtered, function($v){
    return count($v) > 1;
});

print_r($filtered);

// Now you can loop $filtered and display whatever you want

输出:

Array
(
    [A1] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [address] => A1
                )

            [1] => Array
                (
                    [id] => 2
                    [address] => A1
                )

        )

)

答案 1 :(得分:3)

另一种方法是使用array_column()array_count_values()。然后使用array_filter()删除没有重复项的元素:

$teams = [
 ["id" => 1, "address" => "A1"],
 ["id" => 2, "address" => "A1"] ,
 ["id" => 3, "address" => "A2"]
];

$dups = array_count_values(array_column($teams, 'address'));
$teams = array_filter($teams, function($item) use($dups) {
    return $dups[$item['address']] > 1;
});
print_r($teams);

输出(重新格式化):

Array
(
    [0] => Array([id] => 1, [address] => A1)
    [1] => Array([id] => 2, [address] => A1)
)

答案 2 :(得分:1)

浏览数组,记住哪个团队使用了哪些地址。当一个密钥(地址)存储了多个团队时,您发现了一个副本:

<?php
$teams = [
     ["id" => 1, "address" => "A1"]
    ,["id" => 2, "address" => "A1"]
    ,["id" => 3, "address" => "A2"]
  ];

function findDuplicates($teams) {
  $addresses = [];
  foreach ($teams as $team) {
    if (!isset($addresses[$team["address"]])) {
      $addresses[$team["address"]] = [];
    }
    $addresses[$team["address"]][] = $team["id"];
  }
  foreach ($addresses as $address => $teamsHere) {
    if (count($teamsHere) > 1) {
      echo "Teams with same address (" . $address . "): " . join(",", $teamsHere) . "\n";
    }
  }
}

findDuplicates($teams);

Try it online!

使用array_*函数编辑:一种不那么“笨重”的方法:

<?php
$teams = [
     ["id" => 1, "address" => "A1"]
    ,["id" => 2, "address" => "A1"]
    ,["id" => 3, "address" => "A2"]
  ];

function findDuplicates($teams) {
  $addresses = array_column($teams, "address");
  $counts = array_count_values($addresses);
  return array_filter($teams, function($team) use ($counts) { return $counts[$team["address"]] > 1; });
}

print_r(findDuplicates($teams));

Try it online!