我需要在它们之间创建嵌套的foreach
循环,因为有数组的元素。
示例:
这是从
开始的数组print_r($container);
Array
(
[list1] => Array
(
[0] => Array
(
[id_topic] => 45
[id_topicGroup] => 44
[topic] => topic1 di 44
)
[1] => Array
(
[id_topic] => 46
[id_topicGroup] => 44
[topic] => topic2 di 44
)
[2] => Array
(
[id_topic] => 47
[id_topicGroup] => 44
[topic] => topic3 di 44
)
)
[list2] => Array
(
[0] => Array
(
[id_topic] => 48
[id_topicGroup] => 45
[topic] => topic1 di 45
)
[1] => Array
(
[id_topic] => 49
[id_topicGroup] => 45
[topic] => topic2 di 45
)
[2] => Array
(
[id_topic] => 50
[id_topicGroup] => 45
[topic] => topic3 di 45
)
)
)
这是打印此案例的元素的处理
foreach($container)['list1'] as $el_lista1) {
foreach($container)['list2'] as $el_lista2) {
echo $el_lista1 . " " . $el_lista2 . "<br>\n";
}
}
这是输出
topic1 di 44 topic1 di 45
topic1 di 44 topic2 di 45
topic1 di 44 topic3 di 45
topic2 di 44 topic1 di 45
topic2 di 44 topic2 di 45
topic2 di 44 topic3 di 45
topic3 di 44 topic1 di 45
topic3 di 44 topic2 di 45
topic3 di 44 topic3 di 45
但问题是它必须像我一样在内部管理无限数量的列表和论坛?
我认为我需要根据这些列表的数量在它们之间创建一些内部foreach
循环。你能做这个吗?
答案 0 :(得分:1)
<?php
$arr=Array
(
"list1" => Array
(
"0" => Array
(
"id_topic" => 45,
"id_topicGroup" => 44,
"topic" => "topic1 di 44"
),
"1" => Array
(
"id_topic" => 46,
"id_topicGroup" => 44,
"topic" => "topic2 di 44",
),
"2" => Array
(
"id_topic" => 47,
"id_topicGroup" => 44,
"topic" => "topic3 di 44",
)
),
"list2" => Array
(
"0" => Array
(
"id_topic" => 48,
"id_topicGroup" => 45,
"topic" => "topic1 di 45"
),
"1" => Array
(
"id_topic" => 49,
"id_topicGroup" => 45,
"topic" => "topic2 di 45",
),
"2" => Array
(
"id_topic" => 50,
"id_topicGroup" => 45,
"topic" => "topic3 di 45"
)
)
);
$iterator = new RecursiveArrayIterator($arr);
iterator_apply($iterator, 'traverseStructure', array($iterator));
// from php manual
function traverseStructure($iterator) {
while ( $iterator -> valid() ) {
if ( $iterator -> hasChildren() ) {
traverseStructure($iterator -> getChildren());
}
else {
echo $iterator -> key() . ' : ' . $iterator -> current() .'<br>';
}
$iterator -> next();
}
}
//print according to your need
输出:
id_topic : 45
id_topicGroup : 44
topic : topic1 di 44
id_topic : 46
id_topicGroup : 44
topic : topic2 di 44
id_topic : 47
id_topicGroup : 44
topic : topic3 di 44
id_topic : 48
id_topicGroup : 45
topic : topic1 di 45
id_topic : 49
id_topicGroup : 45
topic : topic2 di 45
id_topic : 50
id_topicGroup : 45
topic : topic3 di 45