【发布时间】: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