How can I not initialize the string?

I have a menu system that uses a drag and drop tree structure to make it easier for the user to change. When javascript serializes a string, it does it like this:

// 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


It is then serialized as:



The problem is that there can be an arbitrary number of sublevels, making it difficult to unserialize. I am using PHP server side to unserialize it, but I am at a loss as to what to do.

Any suggestions are appreciated even when using the serialization method, I'll just hack the code.


source to share

5 answers

You should look into the json_encode / json_decode functions in PHP, the ones that make interacting with Javascript very easy.

In your current serialization format, you are just creating headaches for yourself.



EDIT: For people who voted for months after asking him, the original format of this question did NOT mention json or javascript. So I answered in PHP, as the OP answered in the comments, which he corrected himself after my answer, I left my answer for people who hit this page when they are looking for a PHP answer for this question, although this question is not (now). directly answering it.

hmm ...


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

// do whatever

$var_name2 = unserialize($var_name);


Would this be a good method for you?



I think you can split this line first by "#", then each split result is split on regex exactly by "number" number "so" -> "will not", then "number -> number" etc.
Hopefully that this will help.
Sorry for my English.



How about serializing (instead of your string 1>2>3>>4#5#6>7

) to JSON form like this:

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


Then you can unserialize it with json_decode in PHP.



If you really wanted to use this format, something like this would work, but I think JSON would be much better.


$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;






All Articles