arrayforeach() を操作するために foreach
を使用するコードには 2 つの用途があります:foreach(array_name as $value) { statement; }
foreach(array_name as $key => $value) { statement; }
プログラム例 1:
<?php /*-------------------------------------------------------------------------*/ /* foreach example 1: value only */ echo "foreach example 1: value only ".'<br />'; $a = array(1, 2, 3, 17); foreach ($a as $v) { echo " Current value of ".$a.":". $v."<br />"; } ?>
foreach 例 1: 値のみ
現在の値$a: 1
$a の現在値: 2
$a の現在値: 3
$a の現在値: 17
/*-------------------------------------------------------------------------*/ /* foreach example 2: value (with key printed for illustration) */ echo '<br />'.'<br />'."foreach example 2: value (with key printed for illustration) ".'<br />'; $a = array(1, 2, 3, 17); $i = 0; /* for illustrative purposes only */ foreach ($a as $v) { echo ""$a[$i] => $v".'<br />'; $i++; } // 程序运行结果 foreach example 2: value (with key printed for illustration) $a[0] => 1 $a[1] => 2 $a[2] => 3 $a[3] => 17
/*-------------------------------------------------------------------------*/ /* foreach example 3: key and value */ echo '<br />'.'<br />'."foreach example 3: key and value ".'<br />'; $a = array( "one" => 1, "two" => 2, "three" => 3, "seventeen" => 17 ); foreach ($a as $k => $v) { echo ""$a[$k] => $v".'<br />'; } // 程序运行结果 foreach example 3: key and value $a[one] => 1 $a[two] => 2 $a[three] => 3 $a[seventeen] => 17
/*-------------------------------------------------------------------------*/ /* foreach example 4: multi-dimensional arrays */ echo '<br />'.'<br />'."foreach example 4: multi-dimensional arrays ".'<br />'; $a = array(); $a[0][0] = "a"; $a[0][1] = "b"; $a[1][0] = "y"; $a[1][1] = "z"; foreach ($a as $v1) { foreach ($v1 as $v2) { echo "$v2"n"; } } // 程序运行结果 foreach example 4: multi-dimensional arrays a b y z
/*-------------------------------------------------------------------------*/ /* foreach example 5: dynamic arrays */ echo '<br />'.'<br />'."foreach example 5: dynamic arrays ".'<br />'; foreach (array(1, 2, 3, 4, 5) as $v) { echo "$v"n"; } // 程序运行结果 foreach example 5: dynamic arrays 1 2 3 4 5
$messageNav['首页'] =ROOT_PATH; $messageNav['人才交流'] ="#" $messageNav['动态专栏'] ="hragent/cn/" <?php $i = 0;foreach ($messageNav as $key=>$value):?> <?php if ($i != count($messageNav) - 1):?> <a href="<?=$value?>"><?=$key?></a>> <?php else:?> <a href="<?=$value?>" class="onlink"><?=$key?></a> <?php endif;?> <?php $i++;endforeach;?>
以上がPHPでforeachを使用する2つの方法の紹介の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。