0

我已经在互联网上查看过这个问题,但只有在尝试将数组传递给 foreach 并在内部更改它时才会出现问题。我的问题更容易和令人困惑。我有 2 个全局变量:

$type="";
$rule="";

我有这个代码:

foreach($cartasxml->children() as $child) {
    $str="insert into cards (title,cost,color,loyalty,type,pow,tgh,hand,life,rules,set,rarity,number,artist,flavor,cost) values('{{{".$child->name."}}}',";
if(isset($child->typelist))
    {
        foreach($child->typelist as $a)
            $type .= "|" . str_replace("{","[",str_replace("}","]",$a->type));
        $str.="'{{{".substr($type,1)."}}}',";
    }
    else
        $str.="NULL,";

在 foreach 结束时,我会:

$type="";
$rule="";

所以,当我通过打印 $str 看到 $type 的值时,它只显示我包含的最后一个。也许是一个escope问题,但我仍然不知道如何解决它。

有人吗?

4

2 回答 2

0

也许您可以使用数组将所有值推入其中

$type_array = array();
$str_array = array();
foreach($cartasxml->children() as $child) {
    $str="insert into cards (title,cost,color,loyalty,type,pow,tgh,hand,life,rules,set,rarity,number,artist,flavor,cost) values('{{{".$child->name."}}}',";
if(isset($child->typelist))
    {
        foreach($child->typelist as $a)
            $type .= "|" . str_replace("{","[",str_replace("}","]",$a->type));
        $str.="'{{{".substr($type,1)."}}}',";

array_push($type_array,$type);
array_push($str_array,$str);

    }
    else
        $str.="NULL,";


print_r($type_array);
print_r($str_array);
于 2012-09-06T06:51:47.883 回答
0

尝试这个:

$type = implode('|', 
                array_map(function($a)
                           { return str_replace("{","[",str_replace("}","]",$a->type)) },
                          $child->typelist));
$str .= "'{{{".$type."}}}',";
于 2012-09-06T07:29:44.357 回答