鄔瑞瑞
鄔瑞瑞

Reputation: 15

how to make json string by using php array?

This is the target jason string:

{"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"}]}

This is the php array that i made:

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

i am trying to turn this array into the json string above, using:

$data_string=json_encode( $rule );

but it doesnt work :(

i know the array is really non-sense, i am really new to php. Could somebody help me?

Upvotes: 0

Views: 44

Answers (1)

u_mulder
u_mulder

Reputation: 54831

Your array should be:

$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")),  
);

After that json_encode function will do all the work for you:

$data_string = json_encode($rule);

Upvotes: 3

Related Questions