Search code examples
phparraysregexstdclassrecursive-backtracking

Converting string containing multidimensional array keys and values PHP


I use TPP API for check domain availability and domain register but i receive response in string.

  1. Get Session, return stringOK: t73484678463765

  2. Domain check, return string woohoo123.nz: OK: Minimum=1&Maximum=2

  3. In other case, return string woohoo123.nz: ERR: 102, This is message

When It return OK it has & in child but when ERR that time it has ,

I want convert return string into array

such as input woohoo123.nz: OK: Minimum=1&Maximum=2 and output following array

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

input woohoo123.nz: ERR: 102, This is message and output following array

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

I like more to reuse code, I prefer recursive and callback but not sure in this case.


Solution

  • Not 100% sure if this is what you are looking for. It works for your examples, but will only continue to work if the input strings follow that format strictly.

        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"));