[英]Building array from other arrays
我试图从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
)
有什么建议吗? 谢谢!
可能应该这样做(以替换主循环内容):
$id = (string)$newChild->class['id'];
$code = (string)$newChild->code;
$family = (string)$newChild->family;
$items[$code] = array(
'family' => $family,
'classId' => $id,
);
编辑
忘记使用$newChild
而不是$xmlNew1
。
我不了解您的层次结构,因为我对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
)
我喜欢@Jack在这里提出的建议 ,首先将要提取的值分配给它们自己的变量,然后创建条目。
$newItem = array(
'family' => $family,
'classId' => $id,
);
$test[$code] = $newItem;
自然,您必须将其放入迭代中。 迭代完成后, $test
数组应具有所需的格式。
我希望这是有帮助的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.