php - 如何将 2 个数组分组

标签 php arrays algorithm syntax

我有 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[1-21]中的$customer[0]=1,我想通过在$customer考虑来对这2个数组进行分组$head[1-21] 不会有值 1,例如在 $head[1] 中有值 1,因此删除 $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  )

请帮我解决这个问题。

最佳答案

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

Notice: Undefined offset

我刚刚替换了您的 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

关于php - 如何将 2 个数组分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39188598/

相关文章:

c++ - 需要澄清这个执行乘法的循环

php - mySQL 查询,分组依据然后按最近分组的顺序排序?

c - 分段故障

php - 命令调用服务中的 Symfony 进度条

javascript - 通过键从对象合并到对象数组

javascript - 无法访问对象数组

string - 计算可被 6 整除的子序列数的高效算法

c - 在二叉搜索树上找到第一个大于 X 的键

php - 从第三个表中获取值(value)

php - 如何在 PHP 中比较关联数组与 result_array