从PHP数组转换为C#字典

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了从PHP数组转换为C#字典脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我是C#编程的初学者.请帮我把这个代码示例用 PHP重写为C#:

<?PHP
  $final = array('header' => array(),'data' => array());
  $final['header'] = array('tITle' => 'test','num' => 5,'limit' => 5);

  foreach ($results as $name => $data)
  {
    $final['data'][] = array('Primary' =>'PRimary','secondary' => 'Secondary','image' => 'test.png','onclick' => 'alert('You clicked on the Primary');');
  }

  header('Content-tyPE: application/json');
  echo json_encode(array($final));
?>

我试图做这样的事情,但没有成功.

Dictionary<string,string> final = new Dictionary<string,string>();
stringArray.Add("header","data");

解决方法

“最简单”的方法是Dictionary< Object,Object>.由于PHP对数据类型如此松散,因此Object会为您提供更大的灵活性.那么.NET将根据需要将值设为 box.就像是:

/* $final */
IDictionary<Object,Object> final = new Dictionary<Object,Object>();

/* $final["header"] */
// by keeping this separated then joining it to final,you avoid having
// to cast it every time you need to reference it since it's being Stored
// as an Object
IDictionary<Object,Object> header = new Dictionary<Object,Object> {
    { "title","Test" },{ "num",5 },{ "limit",5 }
};
// above short-hand declaration is the same as doing:
// header.Add("title","Test");
// header.Add("num",5);
// header.Add("limit",5);
final.Add("header",header);

/* $final["data"] */
IList<Object> data = new List<Object>();
// not sure where `results` comes From,but I'll assume it's another type of
// IDictionary<T1,T2>
foreach (KeyValuePair<Object,Object> kvp in results)
{
    data.Add(new Dictionary<Object,Object> {
        { "primary","Primary" },{ "secondary","Secondary" },{ "image","test.png" },{ "onclick","alert('You clicked on the Primary');" }
    });
}
final.Add("data",data);

请记住,这当然不是最优化的,但确实使它与您正在使用的最接近.

从那里,您可以使用库(如Newtsonsoft Json)并序列化信息.

JsonConvert.SerializeObject(final);

经过测试和工作:

>您的PHP版本:http://ideone.com/NzfIj4
> C#版本(上)

我将$results / results添加为两个值相等(foo-> Foo,bar-> Bar,baz-> Baz),然后将它们序列化为JSON并得到相同的结果:

脚本宝典总结

以上是脚本宝典为你收集整理的从PHP数组转换为C#字典全部内容,希望文章能够帮你解决从PHP数组转换为C#字典所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。