繁体   English   中英

遍历foreach数组

[英]Loop through foreach array

我在遍历数组时每次都获取一个值时遇到问题。 我只想将1值设为灰色,因为我在jquery中调用了该值。 我是新手,很抱歉,如果这太基础了,但是我已经尝试了好几天,把头发拔了!

$designslist = array('design1','design2','design3','design4');
$current_index = 0;
$current_id = current($designslist);
$next = $designslist[$current_index + 1];

foreach( $designslist as $value )
{
  if( $value !== $next )continue;
  $nexts =  $next;
  echo $nexts;
  $current_index++;
}

在我的HTML里面

<a href="#" id="<?php echo $nexts; ?>">next</a>

用jQuery调用ID

$('#design1').on('click',function() {
  $('#web1').removeClass().addClass('big1');
});
foreach( $designslist as $value )

需要是

foreach( $designslist as $i => $value )

$i是数组索引

您可以尝试数组搜索

$tag       = array_search($value, $designslist);
$nexts     = $$designslist[$tag]; 

好的,您似乎正在使用这些“ current_id”和“ next”变量与foreach混合使用。

您可以使用这种foreach语句:

foreach ($designList as $key => $value) {
    echo "The key of $value is $key";
}

当您只想返回唯一值时,应使用“ array_unique ”函数。 尝试这个:

foreach (array_unique($designList) as $key => $value) {
    echo "The key of $value is $key";
}

我知道这与问题无关,但是,正如您所说的那样,您应该遵循一些PHP技巧。

您在变量中混合了snake_case和camelCase。 我建议使用camelCase,但这取决于您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM