如何在PHP中使用foreach循环迭代关联数组?

2021年3月31日17:55:34 发表评论 783 次浏览

给定两个数组arr1和2号大小为n。任务是在foreach循环中迭代两个数组。两个数组可以使用foreach循环合并为一个数组。

数组:PHP中的数组是一种数据结构, 它允许在单个变量下存储相似数据类型的多个元素, 从而节省了为每个数据创建不同变量的工作。数组有助于创建相似类型的元素列表, 可以使用它们的索引或键来访问它们。

例子:

Input : $sides = array('Up', 'Down', 'Left', 'Right')
        $directions = array('North', 'South', 'West', 'East')

Output :
Up => North
Down => South
Left => West
Right => East

范例1:本示例使用foreach循环显示关联数组的元素。

<?php
  
// Declare an associative array
$aso_arr = array (
     "Up" => "North" , "Down" => "South" , "Left" => "West" , "Right" => "East"
);
  
// Use foreach loop to traverse each
// elements of array and display its
// key and value 
foreach ( $aso_arr as $side => $direc ) {
     echo $side . " => " . $direc . "\n" ; 
}
  
?>

输出如下:

Up => North
Down => South
Left => West
Right => East

范例2:本示例使用数组显示带有值的索引。

<?php
  
// Declare an array
$sides = array ( "Up" , "Down" , "Left" , "Right" );
  
// Use foreach loop to display the
// elements of array
foreach ( $sides as $index => $value ) {
     echo "sides[" . $index . "] => " . $value . " \n" ;
}
  
?>

输出如下:

sides[0] => Up 
sides[1] => Down 
sides[2] => Left 
sides[3] => Right

注意:

索引数组的每个条目都类似于一个关联数组, 其中键是索引号。

例如:

$sides = array("00"=>"Up", "01"=>"Down", "02"=>"Left", "03"=>"Right");
$directions = array("00"=>"North", "01"=>"South", "02"=>"West", "03"=>"East");

由于索引在所有索引数组中都是通用的, 因此它可以使用这些索引来访问其他数组中的值。

范例3:

<?php 
  
// Declare and initialize array
$sides = array ( "Up" , "Down" , "Left" , "Right" );
$directions = array ( "North" , "South" , "West" , "East" );
  
// Use foreach loop to display array elements
foreach ( $sides as $index => $side ) {
     echo $side . " => " . $directions [ $index ] . " \n" ;
}
  
?>

输出如下:

Up => North 
Down => South 
Left => West 
Right => East

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: