PHP:如何将关联数组的每个键与其他键进行比较,跳过排列?

PHP: how to compare each key of an associative array to to the others, skipping permutations?

我有这个(看似)简单的PHP问题:
我有一个关联数组(它反映了 DB table 的结构,但这与此处无关),例如:

----------------------------------
 id  | name            | phone
----------------------------------
   1 | alice           | 12345678
   3 | bob             | 56789012
   9 | zorro           | 90123456
 ... | ...             | ...
----------------------------------

我需要遍历数组以比较(比如检查没有两个人具有相同的 phone 号码)每个键与所有其他键,避免重复检查,如 check(1, 3) 和check(3, 1)...(我想我可以根据等效的数学概念命名这些 duplications)。

<?php
  $table = [
    [
      "id" => "1",
      "name" => "alice",
      "phone" => "12345678",
    ], [
    [
      "id" => "3",
      "name" => "bob",
      "phone" => "56789012",
    ], [
    [
      "id" => "9",
      "name" => "zorro",
      "phone" => "90123456",
    ],
  ];
?>

这就是我正在尝试的:

<?php
  foreach ($table as $record1) {
    foreach ($table as $record2) {
      check($record1["phone"], $record2["phone"]);
    }
  }
?>

当然这会重复检查...
通常(例如,在 C language 中),我会按顺序遍历数组,从外循环当前索引旁边的索引开始内循环...但是在 PHP 中,我已经有人告诉我不能按顺序遍历关联数组...:-(

所以问题是:如何遍历 PHP 关联数组以将函数应用于任意一对键,避免排列?

您可以为此使用 in_array:

foreach ($table as $record1) {
   if(in_array($record1["phone"], $table){

   }
}

这会检查数组中是否存在当前值。在这里阅读更多:http://php.net/manual/en/function.in-array.php

试试这个:)

<?php

$data = array(
    array('id'=>'1','name'=>'test1','phone'=>'1231231234'),
    array('id'=>'2','name'=>'test2','phone'=>'1231231235'),
    array('id'=>'3','name'=>'test2','phone'=>'1231231234')
);

// sort and find duplicate numbers
$ch = array();
$duplicate = array();
foreach($data as $k=>$d){
    if(in_array($d['phone'],$ch)){
        $duplicate[] = $k;
    }else{
        $ch[$k]=$d['phone'];
    }
}
// remove duplicated numbers from the initial table array
if($duplicate){
    foreach($duplicate as $r)
        unset($data[$r]);
}
// now we have only unique numbers
echo '<pre>';
print_r($data);
echo '</pre>';

你可以像在 C:

中那样做
$len = count($table);
for($i = 0; $i < $len - 1; $i++)
    for($j = $i + 1; $j < $len; $j++)
        compare table[$i] and table[$j]

如果您的键不是连续的,则遍历键数组(是连续的)而不是实际数组:

$keys = array_keys($table);
$len = count($keys);
for($i = 0; $i < $len - 1; $i++)
    for($j = $i + 1; $j < $len; $j++)
        compare table[keys[$i]] and table[keys[$j]]