2010-11-19 33 views
1

我試圖將我的lat和lng數組傳遞給我的PHP腳本,以便腳本可以將它保存到.txt文件中。將數組從javascript傳遞到PHP的錯誤

我管理序列化我的數組,並將其傳遞給PHP腳本...在PHP方面,我設法反序列化它。但是,當我將數組寫入文件時,文件僅顯示爲「數組數組」(array array)...而不是數值...假設爲「(1.3567,103.124252)(1.3543,103.436435)」。

下面是我的示例代碼(連載):

function serialize(mixed_value) 
    { 
    var _getType = function(inp) { 
    var type = typeof inp, match; 
    var key; 
    if (type == 'object' && !inp) { 
    return 'null'; 
    } 
    if (type == "object") { 
    if (!inp.constructor) { 
     return 'object'; 
    } 
    var cons = inp.constructor.toString(); 
    match = cons.match(/(\w+)\(/); 
    if (match) { 
     cons = match[1].toLowerCase(); 
    } 
    var types = ["boolean", "number", "string", "array"]; 
    for (key in types) { 
     if (cons == types[key]) { 
     type = types[key]; 
     break; 
     } 
    } 
    } 
    return type; 
    }; 
    var type = _getType(mixed_value); 
    var val, ktype = ''; 

    switch (type) { 
    case "function": 
    val = ""; 
    break; 
    case "undefined": 
    val = "N"; 
    break; 
    case "boolean": 
    val = "b:" + (mixed_value ? "1" : "0"); 
    break; 
    case "number": 
    val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value; 
    break; 
    case "string": 
    val = "s:" + mixed_value.length + ":\"" + mixed_value + "\""; 
    break; 
    case "array": 
    case "object": 
    val = "a"; 
    var count = 0; 
    var vals = ""; 
    var okey; 
    var key; 
    for (key in mixed_value) { 
     ktype = _getType(mixed_value[key]); 
     if (ktype == "function") { 
     continue; 
     } 

     okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key); 
     vals += serialize(okey) + 
     serialize(mixed_value[key]); 
     count++; 
    } 
    val += ":" + count + ":{" + vals + "}"; 
    break; 
    } 
    if (type != "object" && type != "array") { 
    val += ";"; 
    } 
    return val; 
    } 

PHP(反序列化,並粘貼到文件):

$data = $_POST['y']; 

$arr = unserialize($data); 

$fp=fopen("route.txt","w+"); 
foreach($arr as $key => $value){ 
fwrite($fp,$value."\t"); 
} 

感謝所有您的幫助! :D

回答

4
  1. 重新設計車輪? :)爲了明確這一目的,已經有JSON,並且有大量的庫用於以幾乎任何語言對JSON進行編碼和解碼。 PHP自帶json_decode
  2. 寫入文件時,$value本身就是一個數組。將數組轉換爲字符串時(如輸出所需),it'll be cast to the string "Array"。使用join(',', $value)輸出用逗號分隔的數組的所有值。
+0

哦加入(','$ value)真的有幫助!! ..非常感謝! :) – Dayzza 2010-11-19 03:34:00

+0

@Jonathan順便說一句,看起來你的JS實際上是用JSON編碼的,但是PHP是使用'unserialize'反序列化的,它不應該能夠理解JSON ...?! – deceze 2010-11-19 03:39:10

+0

嗯不知道它..但使用反序列化管理從數組中獲得值。 – Dayzza 2010-11-19 03:58:54