2012-08-14 138 views
0

我想从simpleXmlElement构建一个新数组。我收到我想要的信息,只是没有在正确的层次结构中。从其他阵列构建阵列

$xmlNew1 = new SimpleXMLElement($responseNew1); 
$test = array(); 
foreach ($xmlNew1->children() as $newChild){ 
    $classIden[] = (string)$xmlNew1->class['id']; 
    $item[] = (string)$xmlNew1->code; 
    $family[] = (string)$xmlNew1->family; 
    for($i=0, $count = count($classIden); $i < $count; $i++) { 
     $test[$item[$i]][$family[$i]]= $classIden[$i]; 
    } 
} 

print_r($test); 

这给了我:

Array 
(
[9522] => Array 
    (
     [Mens Hats] => 44 
    ) 

[9522-NC-NO SIZE] => Array 
    (
     [Mens Hats] => 44 
    ) 

[B287CSQU] => Array 
    (
     [Boys] => 1 
    ) 

,但我想

Array 
(
[9522] => Array 
(
    [family] => Mens Hats 
    [classId] => 44 
) 

什么建议吗?谢谢!

回答

1

这也许应该这样做(更换主回路内容):

$id = (string)$newChild->class['id']; 
$code = (string)$newChild->code; 
$family = (string)$newChild->family; 

$items[$code] = array(
    'family' => $family, 
    'classId' => $id, 
); 

编辑

忘记使用$newChild而不是$xmlNew1

+0

我不需要在foreach抠每一个孩子叫出来? – 2012-08-14 04:30:30

+0

@TylerNichol更新了我的代码。 – 2012-08-14 04:38:47

0

我不知道你的层次结构,因为我不太了解HTML。你已经隐藏了结构。但是,您应该可以按照您寻找的格式直接构建数组。

让我们尽量减少复杂性。假设你有一个包含所有孩子的变量。所以你可以分开迭代并加载这些孩子。装载:

$xmlNew1 = new SimpleXMLElement($responseNew1); 
$newChildren = $xmlNew1->children(); 

我不能说你如果$xmlNew1->children()足够你得到所有你正在寻找的XML元素,但我们只是假设如此。

下一部分是关于迭代。书面当你遍历孩子,你应该建立$test阵列 - 如你部分已经做了:

$test = array(); 
foreach ($newChildren as $newChild) { 
    ... 
} 

现在缺少的部分是在$test创建您的结构:

Array(
    [9522] => Array(
     [family] => Mens Hats 
     [classId] => 44 
    ) 

我喜欢the suggestion @Jack gives此首先将要提取的值分配给自己的变量,然后创建条目。

$newItem = array(
    'family' => $family, 
    'classId' => $id, 
); 
$test[$code] = $newItem; 

当然,你必须将它放入迭代中。迭代完成后,$test数组应该具有您要查找的格式。

我希望这是有帮助的。