Click here to Skip to main content
15,897,187 members
Articles / Programming Languages / PHP

Converting PHP arrays to a C# Dictionary

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
21 Dec 2011CPOL 30.5K   103   4  
PHP array to C# Dictionary conversion.
class PHPArrayParser
    {
        public Dictionary<string, object> Parse(string array)
        {
            Dictionary<string, object> result = new Dictionary<string, object>();
            array = GetRidOfArrayAndBrackets(array);
            while (!IsStringWhiteSpace(array))
            {
                int indexOfAssignment = array.IndexOf("=>");
                string leftPart = array.Substring(0, indexOfAssignment);
                //currentPosition += indexOfAssignment + 2; //now we should be at the next symbol after =>
                leftPart = leftPart.Trim().Trim('\'');
                string rightPart = array.Substring(indexOfAssignment + 2).Trim();
                //check if it's an array
                if (rightPart.Substring(0, 5).ToLower() == "array")
                {
                    //extract the array and pass it recursively to the same function for parsing
                    string extractedArray = GetArrayFromString(rightPart);
                    result.Add(leftPart, Parse(extractedArray));
                    //get rid of the added content 
                    array = array.Replace(array.Substring(0, array.IndexOf(extractedArray) + extractedArray.Length + 1), "");

                }
                else
                {
                    bool quotesInRightSide = false;
                    if ((rightPart.IndexOf('\'') < rightPart.IndexOf(',')) && rightPart.IndexOf('\'') != -1)
                    {
                        quotesInRightSide = true;
                    }
                    string value = "";
                    if (quotesInRightSide)
                    {
                        int indexOfFirstQuote = rightPart.IndexOf('\'');
                        rightPart = rightPart.Remove(0, 1);//TrimStart('\'');
                        int indexOfSecondQuote = rightPart.IndexOf('\'');
                        value = rightPart.Substring(indexOfFirstQuote, indexOfSecondQuote - indexOfFirstQuote + 2).TrimEnd(',').TrimEnd('\'');
                        //get rid of the added content
                        if (value != "")
                            array = array.Replace(array.Substring(0, array.IndexOf(value) + value.Length + 2), "");
                        else
                            array = array.Replace(array.Substring(0, array.IndexOf(',') + 1), "");
                    }
                    else
                    {
                        value = rightPart.Substring(0, rightPart.IndexOf(','));
                        //get rid of the added content
                        array = array.Replace(array.Substring(0, array.IndexOf(value) + value.Length + 2), "");
                    }
                    result.Add(leftPart, value);
                }
            }

            return result;
        }
        private string GetRidOfArrayAndBrackets(string array)
        {
            //this gets rid of the word array and surronding brackets
            int openBrace = array.IndexOf('(');
            int closeBrace = array.LastIndexOf(')');
            array = array.Substring(openBrace + 1, closeBrace - openBrace - 1);
            return array;
        }
        private string GetArrayFromString(string leftPart)
        {
            //the passed string always starts with 'array (' and we need to determine where the closing bracket is.
            //remember, there may be numerous arrays within arrays
            string result = "";
            int counter = 0;
            bool counterEnabled = false; //can't bale out without even entering the brackets
            foreach (char c in leftPart)
            {
                if (c == '(')
                {
                    counter++;
                    counterEnabled = true;
                }
                if (c == ')')
                    counter--;
                result += c;
                if (counter == 0 && counterEnabled)
                    break;
            }
            return result;
        }
        private bool IsStringWhiteSpace(string str)
        {
            foreach (char c in str)
                if (!char.IsWhiteSpace(c))
                    return false;
            return true;
        }
    }

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Writer
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions