使用php从字符串创建数组

时间:2015-03-30 13:34:38

标签: php string

我有一个如下所示的字符串

Final-Recipient: rfc822;test@example.com
Action: failed
Status: 5.1.1
Diagnostic-Code: smtp;550 5.1.1 RESOLVER.ADR.RecipNotFound; not found

我需要将每个值作为关联数组,如

array('Final-Recipient'=>'rfc822;test@example.com',
      'Action'=>'failed',
      'Status'=>'5.1.1',....)

我尝试使用爆炸功能,但它没有给出预期的结果。

    $result = array();
    $temp =  explode(';',$message);
    foreach($temp as $value)
    {
     $temp2   = explode(':',$value);
     $result[$temp[0]] = $result[$temp[1]];     
    }
    print_r($result);

1 个答案:

答案 0 :(得分:4)

<?php
    $str = 'Final-Recipient: rfc822;test@example.com
    Action: failed
    Status: 5.1.1
    Diagnostic-Code: smtp;550 5.1.1 RESOLVER.ADR.RecipNotFound; not found';
        $res = array ();
        foreach (explode (PHP_EOL, $str) as $e) {
            $t = explode (':', $e);
            $res[trim($t[0])] = trim($t[1]);
        }
        var_dump($res);