[英]Array key as variable in foreach - PHP
This is probably very simple ... but I can't figure it out. 这可能非常简单...但是我无法弄清楚。 I need to use array keys as variables. 我需要使用数组键作为变量。 I have three tabs that need to use unique variables to access data. 我有三个选项卡,需要使用唯一的变量来访问数据。
$array = array(
'items' => 'latest',
'itemsFollow' => 'follow',
'itemsExp' => 'expired'
);
while ( ($stuff = current($array)) !== FALSE ) {
echo '<div id="'.key($array).'" class="tab-content grid flex">';
foreach(/*array_key*/ as $item) { //need foreach($items, foreach($itemsFollow and foreach($itemsExp
// do stuff
}
echo '</div>';
next($array);
}
Loop through your array with foreach. 使用foreach遍历数组。 There is no need to loop twice (nested loops) in a one dimensional array. 在一维数组中不需要循环两次(嵌套循环)。 Use if, elseif
or case
statements to do custom stuff depending on the value. 使用if, elseif
或case
语句根据值执行自定义操作。
foreach ($array as $key => $value){
echo '<div id="'.$key.'" class="tab-content grid flex">';
if($value=="latest"){
//do stuff
}
elseif($value=="follow"){
//do stuff
}
elseif($value=="expired"){
//do stuff
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.