php implode pop 可以做到吗?
例如:从数据库字段检索现有数据:a,b,c,d,e 所以现在
$data= "a,b,c,d,e";
例如:要添加的新数据--- cc, gg 保存到数据库中的最终值将被
$finaldatatobeupdatedintodb= "a,b,c,d,e,cc,gg";
检索并添加更多值。
然后将其追加回逗号列表中。
如何纯粹通过内爆和爆炸来做到这一点,而不需要将其放入数组中进行 for 循环来重建/重新添加添加新值的东西?
eg: existing data retrieve from db field: a,b,c,d,e
so now
$data= "a,b,c,d,e";
eg: new data to be added--- cc, gg
final value saved into db will be
$finaldatatobeupdatedintodb= "a,b,c,d,e,cc,gg";
Retrieve out and add in few more values.
Then append it back into the comma list.
How to do it purely with implode and explode, without needing to put it into array to for loop to reconstruct/re-add the thing with new values added?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您确实想使用 explode 和 implode,你可以做这样的事情:
首先,分解你拥有的字符串:
这会给你:
然后,添加新元素:
$new_list
现在是:最后,使用 ',' 作为分隔符来内爆 $new_list :
你会得到 :
当然,如果你从一个数组开始,那就少了一次爆炸;如果您要添加的数据不是数组,则需要再进行一次爆炸...
但是,正如 Rob 指出的,在简单的情况下,你正在呈现,不需要这么复杂的代码:字符串连接就足够了;-)
基于数组/爆炸/内爆的解决方案的优点是,您可以在将最终数组内爆之前对其进行处理一个字符串(例如,您可以对其进行排序)
If you really want to use explode and implode, you could do something like this :
First, explode the string you have :
Which will give you :
Then, add the new elements :
$new_list
is now :And, finally, implode the $new_list, using ',' as a separator :
And you get :
Of course, if you start with an array, that's one less explode to do ; and if the data you want to add is not an array, that's one more explode to do...
But, as Rob pointed out, in the simple case you are presenting, there is no need for such a complicated piece of code : strings concatenations will be more than enough ;-)
The advantage with the array/explode/implode-based solution is that you can work on the final array before imploding it into a string (say, for instance, you can sort it)
这是你所需要的吗?很难准确理解你的问题在问什么。
Is that what you need? It's difficult to understand exactly what your question is asking.
与 Rob 的答案类似,但可能更稳健一些:
或者,如果您的额外值以数组形式出现:
Similar to Rob's answer, but probably a bit more robust:
or, if your extra values are coming in as an array:
您能否详细说明为什么需要在数据库中存储逗号分隔值?通常,您会为不同的离散值使用单独的字段。如果您有固定数量的值,则可以使用 SET 字段类型。
通常最好的解决方案是使用单独的表。维基百科关于数据库规范化的历史可能会有所帮助。
Can you give more details about why you need to store comma-separated values in a database? Normally you would use separate fields for different discrete values. If you have a fixed number of values you could instead use the SET field type.
Normally the best solution is to use a separate table. Wikipedia's age on Database normalization may help.