将内部数组指针前进到下一条记录以填充jquery函数以使用insertAfter


Advance internal array pointer to next record to fill jquery function to use insertAfter

我是一个jquery新手,我正试图用php提供的信息创建一个jquery函数。我正在使用insertAfter对DIV进行排序,以便按值的顺序显示。(也许有一种更简单/更好的方法?)我的问题是,我无法将指针前移到下一个记录来填充foreach循环。

我的PHP:

$my_array = array("PETER"=>"100","LOIS=>"75","BRIAN"=>"25");
arsort($my_array);     

我的jquery:

$(document).ready(function () {
  var peter = $("#peterDIV");
  var lois = $("#loisDIV");
  var brian = $("#brianDIV");
  <?php
   foreach($my_array as $x=>$x_value)
    {
     echo strtolower($x) . ".insertAfter(".strtolower($x).");";
    }
  ?>
});

foreach的结果:

peter.insertAfter(peter);
lois.insertAfter(lois);
brian.insertAfter(brian);

我尝试过使用next()和array_shift(),但我认为我的语法不正确

编辑

期望结果

lois.insertAfter(peter);
brian.insertAfter(lois);

我希望jquery根据从查询到sql数据库的值按顺序显示DIV。

修复您的解决方案:

$my_array = array("PETER"=>"100","LOIS"=>"75","BRIAN"=>"25");
arsort($my_array);
$previous_key = '';
foreach($my_array as $key=>$value)
{
    // Check if first iteration of loop - if it is set the key and skip rest of loop
    if ($previous_key === '')
    {
        $previous_key = $key;
        continue;
    }
    // Same as your solution but sets the second one to be the previous key
    echo strtolower($key) . ".insertAfter(".strtolower($previous_key).");'n";
    // Updates the previous key with the current key
    $previous_key = $key;
}
相关文章: