猿问

将新数组与前一个数组进行比较

我有一个包含 4 个元素的数组


[1, 2, 3, 4]

到目前为止,我正在打印几个数组,每个数组中都有不同的元素,限制在我设置的范围内。


for($i = 0; $i<=100; $i++){//...

到目前为止的输出:


[11, 22, 32, 44]

[22, 33, 44, 45]

[12, 24, 25, 31]

[15, 16, 31, 41]

[22, 33, 44, 45]//already exist

[11, 22, 32, 44]//already exist

...

如何将传出数组与下一个传出数组进行比较,并在与前一个数组相等时删除新数组?


PIPIONE
浏览 267回答 1
1回答

汪汪一只猫

您可以在帮助下为数组创建一个键,implode()并拥有一个set包含此键的数组。如果 key 已经存在,则迭代中的当前数组是一个重复数组,否则它是一个新数组。请记住对当前数组进行排序,因为此处的数字顺序很重要,以便进行正确的键检查。<?php$arr = [&nbsp; &nbsp; &nbsp; &nbsp; [11, 22, 32, 44],&nbsp; &nbsp; &nbsp; &nbsp; [22, 33, 44, 45],&nbsp; &nbsp; &nbsp; &nbsp; [12, 24, 25, 31],&nbsp; &nbsp; &nbsp; &nbsp; [15, 16, 31, 41],&nbsp; &nbsp; &nbsp; &nbsp; [22, 33, 44, 45],&nbsp; &nbsp; &nbsp; &nbsp; [44, 22, 32, 11]&nbsp; &nbsp; ];$set = [];&nbsp; &nbsp;&nbsp;foreach($arr as $curr_array){&nbsp; &nbsp; sort($curr_array);&nbsp; &nbsp; $hash = implode("|",$curr_array);&nbsp; &nbsp; if(isset($set[$hash])) echo "Duplicate",PHP_EOL;&nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; print_r($curr_array);&nbsp; &nbsp; &nbsp; &nbsp; $set[$hash] = true;&nbsp; &nbsp; }}演示:&nbsp;https&nbsp;:&nbsp;//3v4l.org/EXXRu
随时随地看视频慕课网APP
我要回答