dongxun6458 2010-07-01 15:29
浏览 35
已采纳

PHP问题 - 如何用字符串创建数组?

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"...

  • 写回答

4条回答 默认 最新

  • douzong0711 2010-07-01 15:44
    关注

    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 :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题