【发布时间】:2015-01-03 19:13:59
【问题描述】:
我想将以下 javascript 代码转换为 PHP,但我卡住了。 这是javascript:
var string = "(Munich:0.1,Paris:0.2,(Cyprus:0.3,Brussels:0.4)Bern:0.5)Hamburg";
var ancestors = [];
var tree = {};
var tokens = string.split(/\s*(;|\(|\)|,|:)\s*/);
for (var i=0; i<tokens.length; i++) {
var token = tokens[i];
switch (token) {
case '(': // new children
var subtree = {};
tree.children = [subtree];
ancestors.push(tree);
tree = subtree;
break;
case ',': // another branch
var subtree = {};
ancestors[ancestors.length-1].children.push(subtree);
tree = subtree;
break;
case ')': // optional name next
tree = ancestors.pop();
break;
case ':': // optional length next
break;
default:
var x = tokens[i-1];
if (x == ')' || x == '(' || x == ',') {
tree.name = token;
} else if (x == ':') {
tree.length = parseFloat(token);
}
}
}
这个(变量树)的输出是:
{
name: "Hamburg",
children: [
{name: "Munich", length: 0.1},
{name: "Paris", length: 0.2},
{
name: "Bern",
length: 0.5,
children: [
{name: "Cyprus", length: 0.3},
{name: "Burssels", length: 0.4}
]
}
]
}
我将其转换为 PHP 的尝试如下。但是输出完全不同。我认为这与 [] 和 {} 之间的 javascript 差异有关,其中一个创建一个数组,另一个创建一个对象。但我无法让它工作。
$string = "(Munich:0.1,Paris:0.2,(Cyprus:0.3,Brussels:0.4)Bern:0.5)Hamburg";
$ancestors = array();
$tree = array();
$tokens = preg_split('/(:|\,|\(|\))/', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$count = count($tokens);
for ($i=0; $i<$count; $i++) {
$token = $tokens[$i];
switch ($token) {
case '(': // new children
$subtree = array();
$tree['children'] = $subtree;
array_push($ancestors, $tree);
$tree = $subtree;
break;
case ',': // another branch
$subtree = array();
array_push($ancestors[((count($ancestors))-1)]['children'],$subtree);
$tree = $subtree;
break;
case ')': // optional name next
$tree = array_pop($ancestors);
break;
case ':': // optional length next
break;
default:
$x = $tokens[$i-1];
if ($x == ')' || $x == '(' || $x == ',') {
$tree['name'] = $token;
} else if ($x == ':') {
$tree['length'] = $token;
}
}
}
非常感谢任何解决此问题的想法。
【问题讨论】:
-
php 中的引用与 javascript 中的不同。另请查看数组附加功能。您不需要计数减 1,只需使用括号内没有任何内容。
-
假设您对输入字符串将包含哪些类型的字符串有所了解,您可以删除整个内容并将输入字符串转换为可解析的 JSON。
-
如何将您的字符串转换为 JSON,然后使用 json_decode 函数对其进行解码?
-
@meagar 有时我看不到阿甘……所以你当然是完全正确的。无论如何,该字符串实际上非常接近于一个 json(只是带有其他符号。)所以我只是简单地替换了一些字符并使用了 json_decode。完美的 !谢谢大家...
标签: javascript php arrays object