且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PHP中删除逗号分隔列表中的重复值

更新时间:2023-02-18 17:16:42

在处理事物列表时,最容易使用数组。逗号分隔的字符串工作正常,用于显示事物,但是在代码中使用它们并不乐意。考虑到这一点,我建议甚至不要触摸一个逗号,直到你最终显示数据到屏幕。

When dealing with lists of things, it's easiest to use arrays. Comma-separated strings work alright for displaying things, but they're no fun to work with in code. With that in mind, I would recommend not even touching a comma until you finally display the data out to the screen.

不幸的是,这听起来像你已经有逗号分隔的字符串存储在您的数据库中。如果这是您可以改变的内容,您可能需要使用多个表与用户之间的一对多关系查找替代的数据库结构。有很多可以说这个,但这不是你的问题的主题。基本概念称为数据库规范化,正如Havelock已经提到的那样。

Unfortunately, it sounds like you already have comma separated strings stored in your database. If this is something you can change, you may want to look into an alternative database structure using multiple tables with a one-to-many relationship between users and things they like. There's a lot that could be said about this, but it's not the subject of your question. The basic concept is called database normalization, as Havelock has already mentioned.

如果数据库结构无法更改,并且必须使用逗号分隔的列表,只需撤消逗号分隔并将其返回到数组中即可。为此,您可以使用 explode() 功能:

In the event the database structure cannot be changed and you must work the comma-separated lists, simply undo the comma separation and get them back into arrays in PHP. To do this, you'd use the explode() function:

$teststring = '1,2,3';
$test = explode(',', $asdfstring); // array(1, 2, 3)

一旦你有数组,PHP有一些方便的功能排序,删除重复等。您可能最感兴趣的是 array_unique()

Once you have arrays, PHP has some handy features for sorting, removing duplicates, etc. The one you're probably most interested in here is array_unique().

要将其重新输入以逗号分隔的列表显示,只需使用 implode() ,这与 explode()通过使用数组并使用您选择的分隔符(例如,逗号)加入。

To put it back into a comma-separated list for display, simply use implode(), which does the opposite of explode() by taking an array and joining it with the separator of your choice (e.g., comma).

现在,由于您在这里处理了多个列,而您只需要一个列表,您将不得不以多个步骤构建数组。如果这些列中的每一列都可以包含多个值,那么可以对所有这些列执行爆炸措施:

Now since you have multiple columns you're dealing with here, and you only want one list, you're going to have to build the array in multiple steps. If every one of these columns can contain multiple values, you can do the explosion thing on all of them:

$items_like = explode(',', $rows['items_like']);
$first_like = explode(',', $rows['first_like']);
$second_like = explode(',', $rows['second_like']);
$third_like = explode(',', $rows['third_like']);
$merged = array_merge($items_like, $first_like, $second_like, $third_like);

或者如果第一个,第二个和第三个只包含一个项目,你可以这样做: p>

Or if first, second, and third will only contain one item, you could do this:

$items_like = explode(',', $rows['items_like']);
$other_likes = array($rows['first_like'], $rows['second_like'], $rows['third_like']);
$merged = array_merge($items_like, $other_likes);

现在删除重复项:

$likes = array_unique($merged);

现在我们终于准备添加逗号:

Now we're finally ready to add commas:

echo implode(', ', $likes);