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]... )
(source: narod.ru)
I need any how to represent it as table like this in C#
(source: narod.ru)How to do such thing?
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 --> 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());
}
精彩评论