【问题标题】:Loop through foreach array循环遍历 foreach 数组
【发布时间】:2013-12-16 08:15:09
【问题描述】:

我在循环遍历我的数组以每次只获取一个值时遇到问题。我只想灰化 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');
});

【问题讨论】:

  • 在提出问题时,请始终确保缩进您的代码,不要混合制表符和空格,因为您希望人们能够阅读您的代码 =) 在第二个说明中,不要使用 @ 987654324@ 锚。这是从 html 3.2 遗留下来的,在 html5(和 html 4.01)规则下,这个链接实际上会把你带到页面的顶部。
  • 你能解释清楚,你想用厕所做什么[p
  • 你想要的输出是什么??你能告诉你你想用循环做什么吗???
  • //我的数组 Array ( [0] => design1 [1] => design2 [2] => design3 [3] => design4 ) 我想要输出 design1 然后下次我点击链接设计2等
  • 好吧,我已经尝试了所有人推荐的所有方法,但我仍然无法让它做我想做的事。如果其他人有任何建议,请赐教。谢谢大家!

标签: php jquery arrays loops next


【解决方案1】:

好的,您似乎正在使用这些“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,但这取决于您。

【讨论】:

  • //我的数组Array ( [0] => design1 [1] => design2 [2] => design3 [3] => design4 ) $current_id = current($designslist); $next = $designslist[$i + 1];--foreach( $designslist as $i => $value ){if( $value !== $next )continue; $下一个 = $下一个;回声 $nexts; $i++;} 我如何回显 design1 然后下次我点击链接时它应该是 design2 等等
  • 您将需要在您的 JS 中使用一个变量来计算当前的“i”,这样您就可以获得下一个。我认为你应该创建一个新问题,重点放在 JS / JQuery 部分!
【解决方案2】:

你可以试试数组搜索

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

【讨论】:

    【解决方案3】:
    foreach( $designslist as $value )
    

    需要

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

    $i是数组索引

    【讨论】:

    • //我的数组Array ( [0] => design1 [1] => design2 [2] => design3 [3] => design4 ) //设置当前索引? $current_id = current($designslist); //下一个等于 $next = $designslist[$i + 1]; $i = 0; foreach( $designslist as $i => $value ) if( $value !== $next )continue; $下一个 = $下一个;回声 $nexts; $i++;我需要做的是循环遍历我的数组并将设计添加到我的 中,每次单击链接时都会循环。感谢您的所有帮助。
    猜你喜欢
    • 1970-01-01
    • 2010-10-24
    • 2018-07-17
    • 2021-10-11
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    相关资源
    最近更新 更多