note 105749 added to function.json-encode

From: Date: Mon, 12 Sep 2011 11:19:24 +0000
Subject: note 105749 added to function.json-encode
Groups: php.notes 
Request: Send a blank email to php-notes+get-183107@lists.php.net to get a copy of this message
Some time you may need to encode a javascript function into a JSON object. json_encode does not support it yet. array example: $series = array("name"=>"N51", "data"=>array(1024, array("y"=>2048, "events"=>array("mouseOver"=>'function(){$reporting.html(\'description of value\');}') ), 4096) ); json_encode($series); output: {"name":"N51","data":[1024,{"y":2048,"events":{"mouseOver":"function(){$reporting.html('description of value');}"}},4096]} json_encode_jsfunc($series); output: {"name":"N51","data":[1024,{"y":2048,"events":{"mouseOver":function(){$reporting.html('description of value');}}},4096]} The difference is quotes around function, there should not be quotes. function json_encode_jsfunc($input=array(), $funcs=array(), $level=0) { foreach($input as $key=>$value) { if (is_array($value)) { $ret = json_encode_jsfunc($value, $funcs, 1); $input[$key]=$ret[0]; $funcs=$ret[1]; } else { if (substr($value,0,10)=='function()') { $func_key="#".uniqid()."#"; $funcs[$func_key]=$value; $input[$key]=$func_key; } } } if ($level==1) { return array($input, $funcs); } else { $input_json = json_encode($input); foreach($funcs as $key=>$value) { $input_json = str_replace('"'.$key.'"', $value, $input_json); } return $input_json; } } ---- Server IP: 69.147.83.197 Probable Submitter: 46.161.146.34 ---- Manual Page -- http://www.php.net/manual/en/function.json-encode.php Edit -- https://master.php.net/note/edit/105749 Del: integrated -- https://master.php.net/note/delete/105749/integrated Del: useless -- https://master.php.net/note/delete/105749/useless Del: bad code -- https://master.php.net/note/delete/105749/bad+code Del: spam -- https://master.php.net/note/delete/105749/spam Del: non-english -- https://master.php.net/note/delete/105749/non-english Del: in docs -- https://master.php.net/note/delete/105749/in+docs Del: other reasons-- https://master.php.net/note/delete/105749 Reject -- https://master.php.net/note/reject/105749 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#183107) next »