从数组中删除值数组的最佳方法是什么?
我希望能够轻松快速地从大海捞针数组中删除针数组。事实上,我有一个逗号分隔的数字列表(尽管这是我知道的字符串),需要从我从 sql 数据库中的字段中提取的第二个逗号分隔的数字列表中删除。
所以我需要 -
$orig_needle_list = "3456,5678"; haystack 列表位于 mysql 数据库中的一个字段中,并且是“3456,4567,5678,6789” - 所以我基本上想将该字段更新为“4567,6789”
Q1。我应该检索干草堆列表,将两者转换为数组并使用嵌套的 foreach 循环和 array_splice 任何匹配的值来迭代它们吗?
Q2 使用 in_array 可以比嵌套的 foreach 方法更快吗?
Q3 有没有办法通过在 sql 查询中执行此操作来删除中间人并更新字段?
谢谢
I want to be able to easily and quickly delete an array of needles from a haystack array. In actual fact I have a comma separated list of numbers (though this is a string i know) that need to be deleted from a second comma separated list of number that I pull from a field in my sql database.
So I need -
$orig_needle_list = "3456,5678";
The haystack list is in a field in a mysql database and is "3456, 4567, 5678, 6789" - so I basically want to update this field to "4567,6789"
Q1. Should I retrieve the haystack list, convert both to arrays and iterate over them with a nested foreach cycle and array_splice any matched values?
Q2 Can I use in_array to be faster than nested foreach method?
Q3 is there a way to cut out the middle man and update the field by performing this in an sql query?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要迭代事物,有一个名为 array_diff 的函数:
http://www.php.net/manual/en/function.array-diff.php
因此,创建两个逗号分隔列表的数组并使用 array_diff,得到的数组是这两个数组的差值。
在数据库中存储逗号分隔的列表不是一个好主意,因为它破坏了规范化。
you don't need to iterate over things, there's a function called array_diff:
http://www.php.net/manual/en/function.array-diff.php
So create 2 arrays of the comma separated list and use array_diff, the resulting array is the difference of these two.
Storing comma separated lists in a database isn't a good idea because it breaks normalization.
我认为您正在寻找 array_intersect() http://php.net/manual /en/function.array-intersect.php
I think you are looking for array_intersect() http://php.net/manual/en/function.array-intersect.php
试试这个:
try this: