簡體   English   中英

檢查數組中的相同值

[英]Check same value in array

我有以下數組:

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

如何檢查並獲得具有相同地址的團隊? 我的輸出應該是團隊ID 1和2? 考慮到我不能使用硬編碼地址。 數據是動態的,並且來自數據庫。

在php中,laravel。

先感謝您!

首先,您需要按其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
                )

        )

)

另一種方法是使用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)
)

遍歷數組,記住哪個團隊使用哪個地址。 當一個密鑰(地址)中存儲了多個團隊時,您會發現一個重復的副本:

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

在線嘗試!


編輯:使用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));

在線嘗試!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM