【问题标题】:How to group of 2 arrays如何分组 2 个数组
【发布时间】:2016-08-28 06:31:12
【问题描述】:

我有 2 个这样的数组

$head = array(7, 1, 1, 1, 1, 14, 14, 14, 9, 9, 9, 13, 13, 13, 3, 3, 5, 8, 8, 8, 2, 2); //count =22

$customer = array(1, 7, 9, 13, 14, 1, 9, 13, 1, 13, 14, 1, 9, 14, 2, 8, 8, 2, 3, 5, 3, 8); //count=22

我想通过考虑$customer 对这两个数组进行分组,如果$customer[1-21]$head[1-21] 中的$customer[0]=1 将没有值1,例如在$head[1] 中有值@ 987654328@,所以删除$head[1]$customer[1]。然后考虑$customer[6]。值为9。这意味着在$head[7-21]$customer[7-21] 中不会有9 的值。

我正在尝试为这样的概念编写代码。这是我的代码

for ($i = 0; $i < count($head); $i++) {
    for ($j = $i + 1; $j < count($customer); $j++) {

        if ($customer[$i] == $head[$j]) {
            unset($head[$j]);
            unset($customer[$j]);
        }
        if ($customer[$i] == $customer[$j]) {
            unset($head[$j]);
            unset($customer[$j]);
        }
    }
}

print_r($head);

print_r($customer);

结果是 $head 和 $customer 是:

Array ( [0] => 7 [6] => 14 [7] => 14 [13] => 13 [14] => 3 [15] => 3 [16] => 5 [17] => 8 [18] => 8 [19] => 8 [20] => 2 [21] => 2 ) 

Array ( [0] => 1 [6] => 9 [7] => 13 [13] => 14 [14] => 2 [15] => 8 [16] => 8 [17] => 2 [18] => 3 [19] => 5 [20] => 3 [21] => 8 )

我发现这是错误的。因为真正的结果应该是:

Array ( [0] => 7 [6] => 14 [7] => 14  [14] => 3 [15] => 3  ) 

Array ( [0] => 1 [6] => 9 [7] => 13  [14] => 2 [15] => 8  )

请帮我解决这个问题。

【问题讨论】:

  • 问题在于使用 unset,它只是取消设置值但不会重新排列键。

标签: php arrays algorithm syntax


【解决方案1】:

您的逻辑一切正常,但是当您取消设置特定索引时,当您再次对其进行迭代时,所有其他索引都将丢失,然后 i 索引丢失。只需打开错误和警告即可看到

注意:未定义的偏移量

我刚刚替换了您的 uset 以将其分配给 ''。这样你就可以理解了

<?php

$head = array(7, 1, 1, 1, 1, 14, 14, 14, 9, 9, 9, 13, 13, 13, 3, 3, 5, 8, 8, 8, 2, 2); //count =22

$customer = array(1, 7, 9, 13, 14, 1, 9, 13, 1, 13, 14, 1, 9, 14, 2, 8, 8, 2, 3, 5, 3, 8); //count=22


for ($i = 0; $i < count($head); $i++) {
    for ($j = $i + 1; $j < count($customer); $j++) {

        if ($customer[$i] == $head[$j]) {
            $head[$j] = '';
            $customer[$j] = '';
        }
        if ($customer[$i] == $customer[$j]) {
            $head[$j] = '';
            $customer[$j] = '';
        }
    }
}

print_r(array_diff($head, [''])); // remove all the '' entries

print_r(array_diff($customer, [''])); // remove all the '' entries

【讨论】:

  • 是的,我明白了。谢谢你的帮助^^
【解决方案2】:

问题是count() 只返回数组中集合元素的计数。因此,如果您取消设置它们,它将被减少并且您不会到达数组的末尾。要修复,请在开始时计算计数并将其存储在变量中:

$headcount = count($head);
$customercount = count($customer);
for ($i = 0; $i < $headcount; $i++) {
    for ($j = $i + 1; $j < $customercount; $j++) {

        if ($customer[$i] == $head[$j]) {
            unset($head[$j]);
            unset($customer[$j]);
        }
        if ($customer[$i] == $customer[$j]) {
            unset($head[$j]);
            unset($customer[$j]);
        }
    }
}

【讨论】:

  • 哇,我以前从来不知道这个问题。非常感谢您的好心助手。 :)
猜你喜欢
  • 2017-10-24
  • 2012-01-17
  • 1970-01-01
  • 2020-02-25
  • 1970-01-01
  • 1970-01-01
  • 2013-09-02
  • 1970-01-01
  • 2012-05-28
相关资源
最近更新 更多