我有一个DOMNodeList数组,我试图将其转换为多维数组。这是我尝试这样做的:
$array = (object) array();
foreach ($this->timeofday as $key => $node) {
$array->{$key} = (object) array();
if (get_class($node) === 'DOMElement') {
if ($node->hasAttribute('class')) {
if ($node->getAttribute('class') === 'cmil_salong') {
$array->{$key}->salong = $node->nodeValue;
}
if($node->getAttribute('class') === 'cmil_time'){
$array->{$key}->time = $node->nodeValue;
}
if($node->getAttribute('class') === 'mv_3d'){
$array->{$key}->threed = $node->nodeValue;
}
if($node->getAttribute('class') === 'cmil_rs'){
$array->{$key}->freeseats = $node->nodeValue;
}
if($node->getAttribute('class') === 'mv_txt'){
$array->{$key}->textad = $node->nodeValue;
}
}
}
if (get_class($node) === 'DOMAttr') {
if ($node->nodeName === 'href') {
$array->{$key}->href = $node->nodeValue;
}
}
}
产生:
stdClass Object
(
[0] => stdClass Object
(
[salong] => Tokyo
)
[1] => stdClass Object
(
[time] => 15:00
)
[2] => stdClass Object
(
[threed] =>
)
[3] => stdClass Object
(
[freeseats] => 20
)
[4] => stdClass Object
(
[textad] =>
)
[5] => stdClass Object
(
[href] => http://example.com/1
)
And so on..
但预期的结果是:
stdClass Object
(
[1] => stdClass Object
(
[salong] => Tokyo
[time] => 11:30
[threed] =>
[textad] => 1
[freeseats] => 20
[href] => http://example.com/1
)
[2] => stdClass Object
(
[salong] ... And so on
)
答案 0 :(得分:0)
可能是你想要的东西:
$mainKey=-1;$keyCount=0;
$array = (object) array(); $parant = "";
foreach ($this->timeofday as $key => $node) {
if(($keyCount == 0) || $keyCount >= 5) {$keyCount = 0;
$mainKey++;$array->{$mainKey} = (object) array();}
$array->{$mainKey}->{$key} = (object) array();
if (get_class($node) === 'DOMElement') {
if ($node->hasAttribute('class')) {
if ($node->getAttribute('class') === 'cmil_salong') {
$array->{$mainKey}->{$key}->salong = $node->nodeValue;
}
if($node->getAttribute('class') === 'cmil_time'){
$array->{$mainKey}->{$key}->time = $node->nodeValue;
}
if($node->getAttribute('class') === 'mv_3d'){
$array->{$mainKey}->{$key}->threed = $node->nodeValue;
}
if($node->getAttribute('class') === 'cmil_rs'){
$array->{$mainKey}->{$key}->freeseats = $node->nodeValue;
}
if($node->getAttribute('class') === 'mv_txt'){
$array->{$mainKey}->{$key}->textad = $node->nodeValue;
}
}
}
if (get_class($node) === 'DOMAttr') {
if ($node->nodeName === 'href') {
$array->{$mainKey}->{$key}->href = $node->nodeValue;
}
}
}
应该有父节点检查或节点是5然后计算节点并相应地更改主数组索引。