让我有一个像这样的数组
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
?>
<div id="3">
<!-----result of foreach loop---->
</div>
<div id="1">
<?php
foreach ($age as $key => $value) {?>
<p><?php echo $value;?></p>
<?php
}
?>
</div>
<div id="2">
<!-----result of foreach loop---->
</div>
<?php
?>
我想在<div id="2">
和<div id="3">
中打印相同的结果,没有循环遍历数组,我只想使用循环一次。
答案 0 :(得分:3)
<?php
$pAge = "";
foreach ($age as $key => $value) {
$pAge .= "<p>" . $value . "</p>";
}
?>
<div id="3">
<?= $pAge; ?>
</div>
<div id="1">
<?= $pAge; ?>
</div>
答案 1 :(得分:2)
您可以尝试将所有这些变量放入变量中,然后将它们回显出去 像这样的东西 -
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
$display_str = "";
foreach ($age as $key => $value) {
$display_str .= $value;
}
?>
<div id="1">
<?php echo $display_str;?>
</div>
<div id="2">
<!-----result of foreach loop---->
<?php echo $display_str;?>
</div>
答案 2 :(得分:2)
只需将html存储在div部分之前并打印三次:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
$htmlString = '';
foreach ($age as $key => $value)
{
$htmlString .= '<p>'.$value.'</p>';
}
?>
<div id="3">
<?=$htmlString?>
</div>
<div id="1">
<?=$htmlString?>
</div>
<div id="2">
<?=$htmlString?>
</div>
答案 3 :(得分:1)
你可以这样做:
<div id="1">
<?php
$html="";
foreach ($age as $key => $value) {
$html .= "<p>".$value."</p>";
}
echo $html;
?>
</div>
<div id="2">
<?php echo $html; ?>
</div>
答案 4 :(得分:1)
只需将结果值存储在使用的数组中,如下所示:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
?>
<div id="3">
<!-----result of foreach loop---->
</div>
<div id="1">
<?php
$res = array();
foreach ($age as $key => $value) {?>
<p><?php
$res[] = $value;
echo $value;?></p>
<?php
}
?>
</div>
<div id="2">
<!-----result of foreach loop---->
<?php
echo '<pre>';
print_r($res); ?>
<p><?php
echo $res[0];
echo $res[1];
echo $res[2];
?></p>
</div>
<?php
?>
答案 5 :(得分:1)
你也可以使用:
<?php
function myfunction($value,$key)
{
echo "$value<br>";
}
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
?>
<div id="3">
<?php array_walk($age,"myfunction"); ?>
</div>
<div id="1">
<?php array_walk($age,"myfunction"); ?>
</div>
<div id="2">
<?php array_walk($age,"myfunction"); ?>
</div>