2

我使用 TPPAPI检查域可用性和域注册,但我在string.

  1. 获取会话,返回字符串OK: t73484678463765

  2. 域检查,返回字符串woohoo123.nz: OK: Minimum=1&Maximum=2

  3. 在其他情况下,返回字符串woohoo123.nz: ERR: 102, This is message

当它返回时,OK&在孩子身上,但当ERR它有,

我想将返回转换stringarray

比如woohoo123.nz: OK: Minimum=1&Maximum=2下面的输入输出array

 [
     'woohoo123.nz' => [
         'OK' => [
             'Minimum' => 1,
             'Maximum' => 2,
         ]
     ]
 ]

输入woohoo123.nz: ERR: 102, This is message输出如下array

 [
     'woohoo123.nz' => [
         'ERR' => [
             'code' => 102,
             'message' => 'This is message',
         ]
     ]
 ]

我更喜欢重用代码,我更喜欢recursivecallback在这种情况下不确定。

4

1 回答 1

1

不是 100% 确定这是否是您正在寻找的。它适用于您的示例,但只有在输入字符串严格遵循该格式时才会继续工作。

    function stringToArray($inputStr) {
    $array = [];

    $topComponents = explode(': ',$inputStr);
    $parametersStr = $topComponents[count($topComponents) -1];
    if (strpos($parametersStr,'&') !== FALSE) {
        $tmpArr = explode('&',$parametersStr);
        foreach ($tmpArr as $val) {
            $comp = explode('=',$val);
            $array[$comp[0]] = $comp[1];
        }
    } else if ($topComponents[count($topComponents) - 2] === "ERR") {
        $tmpArray = explode('ERR: ',$parametersStr);
        $tmpArray = explode(', ',$tmpArray[0]);
        $array = [
            "code" => intval($tmpArray[0]),
            "message" => $tmpArray[1]
        ];
    } else {
        $array = $parametersStr;
    }

    for ($i=count($topComponents) -2; $i >= 0; $i--) {
        $newArray = [];
        $newArray[$topComponents[$i]] = $array;
        $array = $newArray;
    }

    return $array;
}

print_r(stringToArray("OK: t73484678463765"));
于 2016-08-26T03:41:31.097 回答