how to get data to javascript from php using json_encode?

后端 未结 7 2077
梦如初夏
梦如初夏 2020-12-29 12:20

I am trying to map traceroutes to google maps.

I have an array in php with traceroute data as

$c=ip,latitude,longitude, 2nd ip, its latitude, longitu         


        
7条回答
  •  情歌与酒
    2020-12-29 12:41

    This function works for you I guess:

        function json_encode4js($data) {
        $result = '{';
        $separator = '';
        $count = 0;
        foreach ($data as $key => $val) {
    
            $result .= $separator . $key . ':';
            if (is_array($val)){
                $result .= json_encode4js($val).(!$separator && count($data) != $count ? ",":"");
                continue;
            }
            if (is_int($val)) {
                $result .= $val;
            } elseif (is_string($val)) {
                $result .= '"' . str_replace('"', '\"', $val) . '"';
            } elseif (is_bool($val)) {
                $result .= $val ? 'true' : 'false';
            } elseif (is_null($val)) {
                $result .= 'null';
            } else {
                $result .= $val;
            }
    
            $separator = ', ';
            $count++;
        }
    
        $result .= '}';
    
        return $result;
    }
    
    $a = array(
    "string"=>'text',
    'jsobj'=>[
        "string"=>'text',
        'jsobj'=>'text2',
        "bool"=>false
        ],
    "bool"=>false);
    
    var_dump( json_encode4js($a) ); //output: string(77) "{string:"text", jsobj:{string:"text", jsobj:"text2", bool:false}, bool:false}" 
    
    var_dump( json_encode($a));//output: string(85) "{"string":"text","jsobj":{"string":"text","jsobj":"text2","bool":false},"bool":false}"
    

提交回复
热议问题