我有这个PHP数组对应于点击'next'时显示的消息。
Array ( [1] => 1 [4] => 4 [5] => 5 [7] => 7 [13] => 13 )
首先,#1显示,#4是通过Ajax POST检索的(点击“下一步”)。这很有效,你可以在这里看到:
if(isset($_POST['mssID'])) { $current_message = $_POST['nextKey']; }
// the message with that ID shows
然后,问题是我不能在帖子之后在同一个数组中设置当前键(#4)。 下一个问题是我无法在数组中设置prev()和next()。
任何人都知道如何设置正确的current(),prev()和next()?
$ current_message == 4时的预期输出:
<div>message #4</div>
<a href="1">prev</a> | <a href="5">next</a>
答案 0 :(得分:3)
在这里,我的解决方案,我已经为prev和next做了功能。
<?php
$array = array("1" => "11", "7" => "22", "3" => "33");
function gen_next($array,$currentValue)
{
//get array key from the value
$array_key_from_value = array_search($currentValue, $array);
$string_of_keys = implode('|', array_keys($array));
$array_of_keys = explode('|', $string_of_keys);
for($i=0;$i<count($array_of_keys);$i++)
{
if($array_key_from_value == $array_of_keys[$i])
{
if($i == (count($array_of_keys)-1))
{
return "No next value";//the current index is the last of the array, can't set a next
}
else
{
return $array_of_keys[$i+1];//else return the next index
}
}
}
}
function gen_prev($array,$currentValue)
{
//get array key from the value
$array_key_from_value = array_search($currentValue, $array);
$string_of_keys = implode('|', array_keys($array));
$array_of_keys = explode('|', $string_of_keys);
for($i=0;$i<count($array_of_keys);$i++)
{
if($array_key_from_value == $array_of_keys[$i])
{
if($i == 0)
{
return "No prev value";//the current index is the last of the array, can't set a next
}
else
{
return $array_of_keys[$i-1];//else return the next index
}
}
}
}
?>
<强>用法强>
var_dump(gen_next($array, '33'));
var_dump(gen_prev($array, '22'));
string 'No next value' (length=13)
string '1' (length=1)
答案 1 :(得分:1)
你可以这样做,
$array = array( 1 => 1, 4 => 4, 5 => 5, 7 => 7, 13 => 13 ) ;
// your initial array
$current_message = 4;
// current is 4
$keys = array_keys($array);
// make array indexed from 0
$search = array_search($current_message , $keys);
// search inside indexed array the key
$prev = $next = 0; // initailize to 0
if($current_message != reset($array)) // check if current is not first
$prev = $keys[$search-1];
if($current_message != end($array)) // check if current is not last
$next = $keys[$search+1];
var_dump($prev,$next);
会给你
int(1)
int(5)
但是,如果在填充数组时将数组编入索引,那么它将减少一行。