我有一个数组:
$input = array("a", "b", "c", "d", "e");
用户可以选择一个字母,然后我想分配他们选择的内容,并将一个值分配给变量。
E.g。用户选择“c”产生:
$userVariable = 'c';
$input = array("a", "b", "c", "d", "e");
// do something to $input and produce
$letter1 = 'b';
$letter2 = 'c';
$letter3 = 'd';
我在猜array_slice()
但是从阅读它开始我找不到一种可以选择前后值的方法,而且实际上似乎是在数字值“切片”而不是实际值。
另外,如果选择“a”,那么我需要返回a,b,c
,如果选择“e”,我想返回e,d,c
这可能吗?
答案 0 :(得分:2)
<?php
$input = array("a", "b", "c", "d", "e");
$find = 'c';
$key = array_search($find, $input); //get the key index of user input
echo $key;
echo '<br />';
$total = count($input);
if ( $key === 0)
{
echo $input[$key];
echo $input[$key+1];
echo $input[$key+2];
}
else if( $key === ($total-1) )
{
echo $input[$key-2];
echo $input[$key-1];
echo $input[$key];
}
else
{
echo $input[$key-1];
echo $input[$key];
echo $input[$key+1];
}
&GT;
答案 1 :(得分:0)
$input = array("a", "b", "c", "d", "e");
$userChoice="c";
for ($i=0; $i<count($input); $i++)
{
if ($input[$i]==$userChoice)
{
$letter1=$input[$i-1];
$letter2=$input[$i];
$letter3=$input[$i+1];
}
}
echo "Letter 1: ".$letter1."<br />";
echo "Letter 2: ".$letter2."<br />";
echo "Letter 3: ".$letter3;
答案 2 :(得分:0)
首先获取他们键入的数组值的索引
$key = array_search('c', $input );
然后
if(isset($input[$key-1]))
$letter1 = $input[$key-1];
$letter2 = $input[$key];
if(isset($input[$key+1]))
$letter3 = $input[$key+1];
答案 3 :(得分:0)
<?php
$userVariable = 'c';
$input = array("a", "b", "c", "d", "e");
foreach ($input as $idx => $value) {
if ($userVariable == $value) {
if ($idx == 0) {
print $input[$idx] . "," .$input[$idx+1] . "," .$input[$idx+1];
} else {
if ($idx == count($input) - 1) {
print $input[$idx-2] . "," .$input[$idx-1] . "," .$input[$idx];
} else {
print $input[$idx-1] . "," .$input[$idx] . "," .$input[$idx+1];
}
}
}
}
?>
答案 4 :(得分:0)
尝试以下代码:
$input = array("a", "b", "c", "d", "e");
$key = array_search('a', $input);
echo $prev = (isset($input[$key - 1]))?$input[$key - 1]:"";
echo $selected = $input[$key];
echo $next = (isset($input[$key + 1]))?$input[$key + 1]:"";
答案 5 :(得分:0)
<?php
$userVariable = 'e';
$input = array("a", "b", "c", "d", "e");
// get position of $userVar in $input
$pos = array_search($userVariable,$input);
if($pos == 0){
// the first one
$letter1 = $input[$pos];
$letter2 = $input[$pos+1];
$letter3 = $input[$pos+2];
}elseif($pos==count($input)-1){
// the last one
$letter1 = $input[$pos-2];
$letter2 = $input[$pos-1];
$letter3 = $input[$pos];
}else{
// others
$letter1 = $input[$pos-1];
$letter2 = $input[$pos];
$letter3 = $input[$pos+1];
}
var_dump($letter1,$letter2,$letter3);
?>
答案 6 :(得分:0)
使用array_slice():
$input = array("a", "b", "c", "d", "e");
$choice = 'e';
$result = array_slice(
$input,
((array_search($choice, $input) - 1) > 0) ? array_search($choice, $input) - 1 : 0,
3
);
var_dump($result);
虽然如果选择e,d,c
但未提供e
,只需d,e