我在网上找到了以下代码。我很乐意在自己的项目中使用它。
http://dbushell.github.io/Nestable/
这个可拖动的jquery生成树结构生成一个序列化数组。 在我看来,这是一个序列化的javascript数组。
[{"id":1,"children":[{"id":3}]},{"id":2,"children":[{"id":4},{"id":9,"children":[{"id":5,"children":[{"id":6},{"id":7},{"id":8}]}]}]},{"id":11},{"id":12,"children":[{"id":10}]}]
对于我能找到的内容,我应该使用 parse_str ,并且应该这样做。
但无济于事。 生成的数组是空的。
我尝试了以下测试代码:
<?php
$Str = '[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]';
parse_str($Str, $values);
print_r($values);
?>
我希望有人看到我忽略的东西。
提前致谢!
答案!
我忽略的是,这不是Javascript序列化的 数组,而是JSON编码的字符串。
如下所示,我应该使用JSON解码。
$Str = json_decode('[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]');
这将提供如下所示的结果。
如果我想将结果用作数组而不是提供给我的数组 应该使用以下函数将对象转换为有效 阵列:
function toArray($obj){ if (is_object($obj)) $obj = (array)$obj; if (is_array($obj)) { $new = array(); foreach ($obj as $key => $val) { $new[$key] = toArray($val); } } else { $new = $obj; } return $new; } $Str = toArray($Str);
(*这是我复制自: How do I convert an object to an array? *)
答案 0 :(得分:1)
不,你应该像这样使用json_decode()
<?php
$Str = '[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]';
$php_array = json_decode($Str);
// and just in case there is an error while decoding
if ( json_last_error() > 0 ) {
echo json_last_error_msg();
}
print_r($php_array);
?>
将生成输出:
Array
(
[0] => stdClass Object
(
[id] => 1
)
[1] => stdClass Object
(
[id] => 2
[children] => Array
(
[0] => stdClass Object
(
[id] => 3
)
[1] => stdClass Object
(
[id] => 4
)
[2] => stdClass Object
(
[id] => 5
[children] => Array
(
[0] => stdClass Object
(
[id] => 6
)
[1] => stdClass Object
(
[id] => 7
)
[2] => stdClass Object
(
[id] => 8
)
)
)
[3] => stdClass Object
(
[id] => 9
)
[4] => stdClass Object
(
[id] => 10
)
)
)
[2] => stdClass Object
(
[id] => 11
)
[3] => stdClass Object
(
[id] => 12
)
)
或者,如果您希望将整个数据集作为数组返回而不是原始数据中存在的对象,则可以将第二个参数添加到json_decode($Str, true)
,它将全部位于数组中:
<?php
$Str = '[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]';
$php_array = json_decode($Str, true);
// and just in case there is an error while decoding
if ( json_last_error() > 0 ) {
echo json_last_error_msg();
}
print_r($php_array);
?>
给出这个结果:
Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 2
[children] => Array
(
[0] => Array
(
[id] => 3
)
[1] => Array
(
[id] => 4
)
[2] => Array
(
[id] => 5
[children] => Array
(
[0] => Array
(
[id] => 6
)
[1] => Array
(
[id] => 7
)
[2] => Array
(
[id] => 8
)
)
)
[3] => Array
(
[id] => 9
)
[4] => Array
(
[id] => 10
)
)
)
[2] => Array
(
[id] => 11
)
[3] => Array
(
[id] => 12
)
)
答案 1 :(得分:1)
只需使用$('.grabPromo').click(function(e){
$('.slideUp').slideDown(300 , function() {
$(this).slideUp(300);
});
});
json_decode