|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
基础这个工具是个比较笼统的概念,如果你之前学习过c语言,c语言被认为是foreach
(PHP4,PHP5)
Theforeachconstructprovidesaneasywaytoiterateoverarrays.foreachworksonlyonarraysandobjects,andwillissueanerrorwhenyoutrytouseitonavariablewithadifferentdatatypeoranuninitializedvariable.Therearetwosyntaxes:- foreach(array_expressionas$value)statementforeach(array_expressionas$key=>$value)statement
复制代码 Thefirstformloopsoverthearraygivenbyarray_expression.Oneachiteration,thevalueofthecurrentelementisassignedto$valueandtheinternalarraypointerisadvancedbyone(soonthenextiteration,youllbelookingatthenextelement).
Thesecondformwilladditionallyassignthecurrentelementskeytothe$keyvariableoneachiteration.
Itispossibletocustomizeobjectiteration.
Note:
Whenforeachfirststartsexecuting,theinternalarraypointerisautomaticallyresettothefirstelementofthearray.Thismeansthatyoudonotneedtocallreset()beforeaforeachloop.
Asforeachreliesontheinternalarraypointer,changingitwithintheloopmayleadtounexpectedbehavior. Inordertobeabletodirectlymodifyarrayelementswithintheloopprecede$valuewith&.Inthatcasethevaluewillbeassignedbyreference.
Referencing$valueisonlypossibleiftheiteratedarraycanbereferenced(i.e.ifitisavariable).Thefollowingcodewontwork:
WarningReferenceofa$valueandthelastarrayelementremainevenaftertheforeachloop.Itisrecommendedtodestroyitbyunset().
Note:
foreachdoesnotsupporttheabilitytosuppresserrormessagesusing@. Youmayhavenoticedthatthefollowingarefunctionallyidentical:
Thefollowingarealsofunctionallyidentical:
Somemoreexamplestodemonstrateusage:
Unpackingnestedarrayswithlist()
(PHP5>=5.5.0)
PHP5.5addedtheabilitytoiterateoveranarrayofarraysandunpackthenestedarrayintoloopvariablesbyprovidingalist()asthevalue.
Forexample:
Theaboveexamplewilloutput:Youcanprovidefewerelementsinthelist()thanthereareinthenestedarray,inwhichcasetheleftoverarrayvalueswillbeignored:
Theaboveexamplewilloutput:Anoticewillbegeneratediftherearentenougharrayelementstofillthelist():
Theaboveexamplewilloutput:- Notice:Undefinedoffset:2inexample.phponline7A:1;B:2;C:Notice:Undefinedoffset:2inexample.phponline7A:3;B:4;C:
复制代码 多个成员之间重复做相同的工作,很容易因为交流沟通的时候没有进行一致性的文档要求而出现不明错误,严重影响开发进度,导致在预定时间内无法完成该项目或者完成的项目跟原先计划所要实现的项目功能不符合。 |
|