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:
1>2>3>>4#5#6>7
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
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 ...
So:
$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?
source to share
If you really wanted to use this format, something like this would work, but I think JSON would be much better.
<?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);
source to share