views:

209

answers:

1

So I have such string (recived from php server... normal print_r of array)

 Array ( [item_number_in_array] => Array ( [id] => id_value [title] title_value_as_string_vith_spaces [content] => content_value_as_string_vith_spaces ) [item_number_in_array]... )

alt text

I need any how to represent it as table like this in C#

alt text

How to do such thing?

+1  A: 

I'm not so skilled in php but I think you should arrange the given string in something more similar to a grid (like a csv-like file) then easily parse it with c#.

As the string you give is basically php, you could parse it with a php parser (direclty in php or in c#) and analysing lexems you can build your grid.

Look here for some hints --> http://stackoverflow.com/questions/1430778/fast-parsing-of-php-in-c

EDIT 1: anyway, if the struct is always the same (i.e. Array ( [0] => Array( "no array inside" ) [1] => Array( "no array inside" ) ...) you could parse it in c# with Regex

EDIT 2: I mean something like this (it's very rough but tested):

Regex arrayRegex = new Regex(@"Array[ \t]*\((.+)\)");
Regex rowRegex = new Regex(@"\[([^\]]+)\] => Array \( ([^)]+)[ \t]*\)");
Regex entryRegex = new Regex(@"\[([^\]]+)\] => ([^\]\[]+)");

var rows = new List<SortedDictionary<string,string>>();
var matches = arrayRegex.Matches(textToParse);
foreach (Match match in matches)
{
    if (match.Groups.Count != 2)
        throw new Exception("Invalid array");
    var rowsMactches = rowRegex.Matches(match.Groups[1].Value);
    foreach (Match rowMatch in rowsMactches)
    {
        var rowDict = new SortedDictionary<string, string>();
        if (rowMatch.Groups.Count != 3)
            throw new Exception("Invalid row");
        var entryMatches = entryRegex.Matches(rowMatch.Groups[2].Value);
        foreach (Match entryMatch in entryMatches)
        {
            if (entryMatch.Groups.Count != 3)
                throw new Exception("Invalid entry");
            string key = entryMatch.Groups[1].Value;
            string val = entryMatch.Groups[2].Value;
            rowDict.Add(key, val);
        }
        rows.Add(rowDict);
    }
}

// use the first row to build the columns (N.B. we suppose all dictionaries have the same keys)
var firstRow = rows.First();
DataTable dt = new DataTable();
foreach (string colName in firstRow.Keys)
{
    dt.Columns.Add(colName);
}
foreach (var row in rows)
{
    dt.Rows.Add(row.Values.Cast<object>().ToArray());
}
digEmAll