V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
dadazhang
V2EX  ›  PHP

怎么吧一个字符串冒号前面的值当做数组的键,把冒号后面的值当做数组的值

  •  1
     
  •   dadazhang · 2017-04-11 11:14:51 +08:00 · 2794 次点击
    这是一个创建于 2565 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Domain Name: dada.com,
    Registry Domain ID: 102993_DOMAIN_COM-VRSN,
    Registrar WHOIS Server: whois.pairNIC.com,
    Registrar URL: https://www.pairNIC.com,
    Updated Date: 2014-02-03T19:00:24+0000Z,
    Creation Date: 1995-03-04T05:00:00+0000Z,
    Registrar Registration Expiration Date: 2018-03-05T05:00:00+0000Z,
    Registrar: pairNIC INC,
    Registrar IANA ID: 99,
    Registrar Abuse Contact Email: [email protected],
    Registrar Abuse Contact Phone: +1.8887247642,
    Domain Status: clientDeleteProhibited,
    Domain Status: clientTransferProhibited,
    Domain Status: clientUpdateProhibited,
    Registry Registrant ID: ,
    Registrant Name: Juan-Carlos Sobrino,
    Registrant Organization: ,
    Registrant Street: 47 Saint Mark's Place ,
    Registrant City: New York,
    Registrant State/Province: NY,
    Registrant Postal Code: 10003,
    Registrant Country: US,
    Registrant Phone: +1.6465551234,
    Registrant Phone Ext:,

    就类似这样的数据,有的冒号后面还是空的值。。。怎么解决。。。。求助

    10 条回复    2017-04-19 12:53:59 +08:00
    silentoy
        1
    silentoy  
       2017-04-11 11:31:14 +08:00   ❤️ 1
    ```php
    $data = explode("\n", $str);
    $res = array();

    foreach ($data as $item) {
    list($key, $value) = explode(":", $item);
    $res[trim($key)] = trim($value, ' ,');
    }

    var_dump($res);
    ```
    kghch
        2
    kghch  
       2017-04-11 11:39:19 +08:00
    lines = data.split(',')
    res = {}
    for line in lines:
    line= line.split(':')
    k = line[0]
    v = ''
    if len(line) > 1:
    v = line[1]
    res[k] = v

    print res
    dadazhang
        3
    dadazhang  
    OP
       2017-04-11 11:59:15 +08:00
    @silentoy 谢谢,完美解决
    kghch
        4
    kghch  
       2017-04-11 12:55:47 +08:00
    #2 ,格式丢了,不好意思。
    nfroot
        5
    nfroot  
       2017-04-11 14:03:06 +08:00
    php 的数组 key 还能用空格啊
    wangjie
        6
    wangjie  
       2017-04-11 14:38:16 +08:00
    let a={}
    data.split(',')
    .map((t)=>{
    let l=t.split(':')
    a[l[0]]=l[1]
    })
    console.log(a)
    Tyanboot
        7
    Tyanboot  
       2017-04-11 23:44:39 +08:00 via Android
    …楼上用 Python 和 JS 回答的是在想啥。
    jea
        8
    jea  
       2017-04-18 13:36:22 +08:00
    @Tyanboot 论语言的多样性
    Balthild
        9
    Balthild  
       2017-04-19 10:55:17 +08:00 via Android
    @jea 这里是 /go/php
    jea
        10
    jea  
       2017-04-19 12:53:59 +08:00
    @Balthild 我的意思是他们[手动滑稽]
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1136 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 23:40 · PVG 07:40 · LAX 16:40 · JFK 19:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.