2009-08-24 23 views
2

我有一個使用拖放樹狀結構,很容易讓用戶修改菜單系統。當JavaScript的序列化字符串,它是通過以下方式:我如何反序列化一個字符串?

// Assume each of these items has an ID on with the respective numbers attached 
Menu Item 1 
    + Menu Item 2 
    + Menu Item 3 
    + Menu Item 4 
Menu Item 5 
Menu Item 6 
    + Menu Item 7 

這將進而獲得序列爲:

1>2>3>>4#5#6>7 

這樣做的問題是,有可能是能級任意數量的,這使得反序列化變得困難。我使用PHP服務器端來反序列化它,但我不知道該怎麼做。

任何建議表示歡迎,甚至序列化的方法,我就破解代碼。

+2

該序列化的字符串看起來不正確。它不應該是1> 2> 3 >> 4#5#6> 7嗎? – karim79 2009-08-24 14:16:33

+0

是的,應該是,好景點 – xenon 2009-08-24 14:19:10

回答

5

你應該看看在PHP json_encode/json_decode功能,那些使用JavaScript交互很容易。

根據您當前的序列化格式,你只是在爲自己創造頭痛。

+0

謝謝,我當時真是個白癡。現在我明白了! – xenon 2009-08-24 15:05:38

1

編輯:爲人民投票下來幾個月有人問後,這個問題的原始格式沒有提及JSON或JavaScript。因此我在PHP中回答,正如OP在我回復後更正自己的評論中回答的那樣,我留下了我的答案,讓他們在尋找此問題的PHP答案時訪問此頁面,即使此問題不是(現在)直接回答。

嗯......

這樣:

$var_name = serialize(array("Menu Item 1, Menu Item 2, Menu Item 3, etc...")); 

// do whatever 

$var_name2 = unserialize($var_name); 

那會是一個很好的方法,供您使用?

+0

對不起,我的錯誤。該菜單由JavaScript準備發送到服務器端進行序列化。 – xenon 2009-08-24 14:16:46

+1

啊沒問題,其他人會回答,因爲這種方法是真正的PHP。 – Dorjan 2009-08-24 14:17:56

1

我認爲你可以先用'#'拆分這個字符串,然後每個拆分結果用正則表達式分割爲「number> number」,所以「>>」不會在那裏,那麼「number >> number」等等上。
希望它有幫助。
對不起,我的英語。

1

什麼序列化(而不是你的字符串1>2>3>>4#5#6>7)成JSON形式是這樣的:

{'1': {'2': {'3': {'4': true}}}, '5': true, '6': {'7': true}} 

然後你可以在PHP中使用json_decode反序列化它。

1

如果你真的想使用這種格式,像這樣的工作,但我覺得JSON會更好。

<?php 

$str = '1>2>3>>4#5#6>7'; 

preg_match_all('~([^\d]+)?([\d]+)~', $str, $matches, PREG_SET_ORDER); 

//$current is the nodes from the top to the node we are at currently 
$current = array(); 
$result = array(); 

foreach ($matches as $item) { 
    $id = $item[2]; 

    if (!$item[1] || $item[1] == '#') { 
     $level = 0; 
    } else { 
     $level = strlen($item[1]);  
    } 

    $tmp = array('id' => $id); 

    $current[ $level ] = & $tmp; 

    if ($level == 0) { 
     $result[] = & $tmp; 
    } elseif (isset($current[ $level - 1 ])) { 
     $parent = & $current[ $level - 1 ]; 
     if (!isset($parent['children'])) { 
      $parent['children'] = array(); 
     } 
     $parent['children'][] = & $tmp; 
     unset($parent); 
    } 

    unset($tmp); 
} 

print_r($result);