【发布时间】:2020-02-11 12:52:42
【问题描述】:
我在 C# 中遇到了字符串问题。我从数据库中得到这个字符串,它包含引号 ("),所以我的程序没有正确读取它。
string attributes = databaseFunctions.GetVariationAttributes(produc_id);
我在数据库中的字符串是
a:3:{s:9:"variation";a:6:{s:4:"name";s:9:"Variation";s:5:"value";s:24:"type a | type b | type c";s:8:"position";s:1:"0";s:10:"is_visible";s:1:"1";s:12:"is_variation";s:1:"1";s:11:"is_taxonomy";s:1:"0";}s:5:"color";a:6:{s:4:"name";s:5:"Color";s:5:"value";s:27:"RED | BLUE | WHITE | ORANGE";s:8:"position";s:1:"1";s:10:"is_visible";s:1:"1";s:12:"is_variation";s:1:"1";s:11:"is_taxonomy";s:1:"0";}s:4:"test";a:6:{s:4:"name";s:4:"TEST";s:5:"value";s:15:"120 | 140 | 160";s:8:"position";s:1:"2";s:10:"is_visible";s:1:"1";s:12:"is_variation";s:1:"0";s:11:"is_taxonomy";s:1:"0";}}
这实际上是 Woocommerce 产品变体属性。我需要获取每个属性,检查它是否用于变体,如果是,获取它的名称和可能的值。
也许你知道怎么做?我正在尝试使用子字符串和 IndexOf 函数(获取第一个和第二个冒号的索引,然后从它们之间获取值并在循环中使用它)
我会感谢您的任何建议
[编辑]
好的,我做到了。这不是最漂亮的解决方案,但它有效。我把它贴在这里,所以其他人可能会在类似的情况下使用它
if(databaseFunctions.CheckVariations(variations))
{
string attributes = databaseFunctions.GetVariationAttributes(produc_id);
List<List<string>> parameters = new List<List<string>>();
List<List<string>> values = new List<List<string>>();
int i_1 = 0;
int i_2 = 0;
//First ':'
int c_1 = attributes.IndexOf(':');
//Second ':'
int c_2 = attributes.IndexOf(':', c_1 + 1);
//First 'a' - number of attributes
int a_1 = Convert.ToInt32(attributes.Substring(c_1 + 1, c_2-c_1 -1));
//For each attribute
for (int i = 0; i < a_1; i++)
{
List<string> parameters_of_attribute = new List<string>();
List<string> values_of_attribute = new List<string>();
//First ':'
int ac_1 = attributes.IndexOf(':', c_2 + 1 + i_1);
//Second ':'
int ac_2 = attributes.IndexOf(':', ac_1 + 1);
//First ':' of a
int kc_1 = attributes.IndexOf(':', ac_2 + 1);
//Second ':' of a
int kc_2 = attributes.IndexOf(':', kc_1 + 1);
//Number of parameter-value pairs
int p_v = Convert.ToInt32(attributes.Substring(kc_1 + 1, kc_2 - kc_1 - 1));
//For each parameter-value pair
for (int j = 0; j < p_v; j++)
{
//First '"' of parameter
int pq_1 = attributes.IndexOf('"', kc_2 + 1 + i_2);
//Second '"' of parameter
int pq_2 = attributes.IndexOf('"', pq_1 + 1);
//Name of parameter
string par = attributes.Substring(pq_1 + 1, pq_2 - pq_1 - 1);
//First '"' of value
int vq_1 = attributes.IndexOf('"', pq_2 + 1);
//Second '"' of value
int vq_2 = attributes.IndexOf('"', vq_1 + 1);
//Value of parameter
string val = attributes.Substring(vq_1 + 1, vq_2 - vq_1 - 1);
parameters_of_attribute.Add(par);
values_of_attribute.Add(val);
i_2 = vq_2 - kc_2;
}
parameters.Add(parameters_of_attribute);
values.Add(values_of_attribute);
i_1 = i_2 + kc_2 - c_2;
i_2 = 0;
}
}
【问题讨论】:
-
该数据应该是一个单独的表或 5 个,而不是一个字符串。但我会假设改变不是那么容易?
-
不可能,这是标准的 WordPress 格式。而且我不是只为一个基础制作应用程序,而是为通用基础制作应用程序,因此它必须使用本机格式
-
编写一个词法分析器和一个解析器。这样做并不难,而且您将有一个正确的解决方案,而不是一些乱七八糟的子字符串和索引。
-
这是 PHP 序列化的输出。格式描述为here。可能已经有 C# 代码浮动在那里专门反序列化它,尽管推荐外部库对于 SO 来说是题外话。
标签: c#