加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

从PHP数组转换为C#字典

发布时间:2020-12-13 17:16:47 所属栏目:PHP教程 来源:网络整理
导读:我是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'][] = ar
我是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并得到相同的结果:

[{“header”:{“title”:”Test”,”num”:5,”limit”:5},”data”:[{“primary”:”Primary”,”secondary”:”Secondary”,”image”:”test.png”,”onclick”:”alert(‘You clicked on the Primary’);”},{“primary”:”Primary”,”onclick”:”alert(‘You clicked on the Primary’);”}]}]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读