PHP问题

编程入门 行业动态 更新时间:2024-10-21 17:21:11
PHP问题 - 如何用字符串创建数组?(PHP Question - How to create an array out of a string?)

在我的数据库中,一些字段设置被序列化并存储。 我这样做的时候:

print_r(unserialized($r['settings']));

我会得到这个:

Array ( [prefix] => [suffix] => [min] => [max] => [allowed_values] => 1|Common 2|Rare 3|Almost Extinct )

我正在尝试基于allowed_values的值创建一个数组,如下所示:

Array ( [1] => Common [2] => Rare [3] => Almost Extinct )

问题是,当我使用explode(“|”,$ r ['allowed_values'])时,我得到:

Array( [0] => 1 [1] => Common 2 [2] => Rare 3 [3] => Almost Extinct )

这是有道理的,但显然不是我所希望的......所以,我只是想知道是否有一种简单的方法来做我在这里尝试的事情? 我想过多次使用爆炸,一次用于空间,一次用于管道,但由于“几乎灭绝”的空间而无法使用......

In my database, some field settings are serialized and stored. When I do this:

print_r(unserialized($r['settings']));

I'll get this:

Array ( [prefix] => [suffix] => [min] => [max] => [allowed_values] => 1|Common 2|Rare 3|Almost Extinct )

I'm trying to create an array based on the values for allowed_values like this:

Array ( [1] => Common [2] => Rare [3] => Almost Extinct )

The problem is, when I use explode("|", $r['allowed_values']), I get:

Array( [0] => 1 [1] => Common 2 [2] => Rare 3 [3] => Almost Extinct )

Which, makes sense, but obviously not what I was hoping for... So, I'm just wondering if there's a simple way to do what I'm trying here? I thought about using explode multiple times, once for spaces, and once for pipes, but that won't work either because of the space in "Almost Extinct"...

最满意答案

尝试这个:

$tab=array(); preg_match_all("/\s*(\d+)\|([^\d]+)/",$r['allowed_values'],$tab); print_r(array_combine($tab[1],$tab[2]));

这应该成功:)

try this:

$tab=array(); preg_match_all("/\s*(\d+)\|([^\d]+)/",$r['allowed_values'],$tab); print_r(array_combine($tab[1],$tab[2]));

this should make the trick :)

更多推荐

Extinct,Almost,Array,电脑培训,计算机培训,IT培训"/> <meta name="descript

本文发布于:2023-08-06 16:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1451205.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!