如何使用php数组制作json字符串?

时间:2015-11-29 08:08:00

标签: php arrays json

这是目标杰森字符串:

{"dpid": 272, "priority": 10, "match": {"nw_src": "192.168.1.1", "nw_dst": "192.168.1.2", "nw_proto": 1, "eth_type": 0x0800}, "actions":[{"type": "DROP"}]}

这是我制作的php数组:

$rule = array(
  "dpid" => 272,
  "priority" => 10,
  "match" => {"nw_src": "$_POST['src']", "nw_dst": "$_POST['dst']", "nw_proto": 1, "eth_type": 0x0800},
  "actions"=> [{"type": "DROP"}],  
);

我正在尝试将此数组转换为上面的json字符串,使用:

$data_string=json_encode( $rule );

但它不起作用:(

我知道数组真的没有意义,我对php很新。有人能帮助我吗?

1 个答案:

答案 0 :(得分:3)

你的数组应该是:

$rule = array(
    "dpid" => 272,
    "priority" => 10,
    "match" => array(
        "nw_src" => $_POST['src'], 
        "nw_dst" => $_POST['dst'], 
        "nw_proto" => 1, 
        "eth_type" => 0x0800 
    ),
    "actions"=> array(array("type" => "DROP")),  
);

之后json_encode函数将为您完成所有工作:

$data_string = json_encode($rule);