我需要将以下数组结构打印为:
Node Title 1
topic 1
topic 2
topic 3
topic 4
asset title1
asset title2
asset title3
我如何使用 foreach - PHP
我所做的是:
foreach($output['fields'] as $key => $value) {
if($key == 'title') {
echo $value;
}
if(count($value['main_topic'])) {
foreach($value['main_topic'] AS $mainkey => $main_topic) {
echo $main_topic['topic_title'];
}
}
}
上面的语法是打印标题。但不是 main_topic 数组。
Array
(
[fields] => Array
(
[nid] => 136
[node_title] => Node title 1
[node_type] => curriculum
[title] => Node title 1
[main_topic] => Array
(
[0] => Array
(
[row_id] => 136
[topic_id] => 411847
[weight] => 10
[topic_title] => topic 1
)
[1] => Array
(
[row_id] => 136
[topic_id] => 411839
[weight] => 2
[topic_title] => topic 2
)
[2] => Array
(
[row_id] => 136
[topic_id] => 411840
[weight] => 3
[topic_title] => topic 3
)
[3] => Array
(
[row_id] => 136
[topic_id] => 411841
[weight] => 4
[topic_title] => topic 4
[subfield] => Array
(
[1] => Array
(
[asset_title] => asset title 1
)
[2] => Array
(
[asset_title] => asset title 2
)
[3] => Array
(
[asset_title] => asset title 3
)
)
)
)
)
)
那是因为你正在迭代所有
$output['fields']
。
永远不会有带有键 $value
的 'main_topic'
,因为键 'main_topic'
包含在 $output['fields']
数组中,因此在 foreach 中仅作为 $key
存在。你想要的数组是$value
你的代码应该是这样的:
foreach($output['fields'] as $key => $value) {
if($key == 'title') {
echo $value;
continue;
}
if($key == 'main_topic' && is_array($value)) {
foreach($value as $main_topic) {
echo $main_topic['topic_title'];
}
}
}
为了用完整的解决方案(包括资产标题)来完成这个答案,下面是我的编写方式。
因为
$output['fields']
是起点,为了使代码更具可读性,我使用 =&
运算符创建对起始节点的引用,这样数组就不会复制到内存中。我对内部 foreach
也做了同样的事情。由于我们不修改数据,引用变量就足够了,并且消耗更少的内存和 CPU:
if (is_array($output['fields'])) {
$node =& $output['fields'];
echo $node['title'];
if(is_array($node['main_topic'])) {
foreach($node['main_topic'] as &$main) {
echo $main['topic_title'];
if(is_array($main['subfield'])) {
foreach($main['subfield'] as &$asset) {
echo $asset['asset_title'];
}
}
}
}
}
else {
echo "no menu";
}
$value
是数组,而不是$key['main_topic']
foreach($output['fields'] as $key => $value) {
if($key == 'title') {
echo $value;
}
if($key == 'main_topic') {
foreach($value as $mainkey => $main_topic) {
echo $main_topic['topic_title'];
}
}
}
试试这个,你需要额外的密钥:
echo $value['main_topic'][$mainkey]['topic_title'];
您的数组部分感到困惑。
尝试(我还没有测试过):
echo $output['node_title']."\n";
foreach ($output['fields'] as $key=>$value)
{
switch ($key)
{
case 'title':
echo $value."\n";
break;
case 'main_topic':
if (count($value) > 0)
{
foreach ($value as $main_block)
{
echo "\t".$main_block['topic_title']."\n";
if (array_key_exists('subfield',$main_block)!==FALSE)
{
foreach ($main_block['subfield'] as $subfield_block)
{
echo "\t\t".$subfield_block['asset_title']."\n";
}
}
}
}
break;
default:
break;
}
}