簡體   English   中英

在 PHP 中,如何判斷哪些值與數組中的特定值相鄰?

[英]In PHP, how can I tell what values are adjacent to a specific value in an array?

我有一個值數組。 假設數組是這樣的:

[apple, banana, coconut, duku, emblica, fig, gooseberry]

假設我知道一個特定的值,“fig”。 我怎么知道它旁邊有哪些值,之前和之后?

$index = array_search("fig", $array);
$before = "";
$after = "";
if($index === false){
    echo "Not found";
}else{
    $before = $index > 0 ? $array[$index - 1] : "";
    $after = ($index + 1) < count($array) ? $array[$index + 1] : "";
}

假設鍵是順序的:

$key = array_search($fruit, 'fig');
if ($key === FALSE) {
    echo 'No figs in array';
} else {
    echo "Before: ", $fruit[$key-1];
    echo "After: ", $fruit[$key+1];
}

你會用

$key = array_search($array); 
$leftVal = $array[$key - 1];
$rightVal = $array[$key + 1];

array_search() function 返回數組中值的索引,然后只需遞增/遞減以查找相鄰值。

接受的答案幾乎是正確的,但它不能很好地處理“缺失”元素。

您可以使用 function array_key_exists() 來驗證鍵是否存在,這也可以作為邊界檢查。

嘗試這個:

<?php

function array_before_after($stext,$array) {
$index = array_search($stext, $array);
$before = "";
$after = "";
    if($index === false){
        echo "Not found";
    }else{
        $before = array_key_exists($index - 1,$array) ? $array[$index - 1] : "";
        $after = array_key_exists($index + 1,$array) ? $array[$index + 1] : "";
    }
    return array($before,$after);
}

$my_array = array( 1 => "apple", 2 => "banana", 3 => "coconut", 6 => "fig", 7 => "gooseberry");

$my_stext = "fig";
$a1 = array_before_after($my_stext, $my_array);
echo "'$a1[0]', '$my_stext', '$a1[1]'\n";

$my_stext = "apple";
$a2 = array_before_after($my_stext, $my_array);
echo "'$a2[0]', '$my_stext', '$a2[1]'\n";

$my_stext = "gooseberry";
$a3 = array_before_after($my_stext, $my_array);
echo "'$a3[0]', '$my_stext', '$a3[1]'\n";

?>

如果你想要前面的值,你可以使用reset()next()

<?php

function array_before_after($stext,$array) {
    $my_array = $array;
    $val = reset($my_array);
    $before = "";
    $after="";
    $lim = count($my_array);
    for ($i=1; $i<$lim; $i++) {
        if ($val == $stext) {
            if ( $i<$lim ) $after=next($my_array);
            break;
        } else {
            $before = $val;
        }
        $val = next($my_array);
    }
    return array($before,$after);
}

$my_array = array( 1 => "apple", 2 => "banana", 3 => "coconut", 6 => "fig", 7 => "gooseberry");

$my_stext = "fig";
$a1 = array_before_after($my_stext, $my_array);
echo "'$a1[0]', '$my_stext', '$a1[1]'\n";

$my_stext = "apple";
$a2 = array_before_after($my_stext, $my_array);
echo "'$a2[0]', '$my_stext', '$a2[1]'\n";

$my_stext = "gooseberry";
$a3 = array_before_after($my_stext, $my_array);
echo "'$a3[0]', '$my_stext', '$a3[1]'\n";

?>
$my_array = ['apple', 'banana', 'coconut', 'duku', 'emblica', 'fig', 'gooseberry'];

echo $my_array[ 5 ]; // Will print fig
echo $my_array[ 4 ]; // Will print emblica
echo $my_array[ 6 ]; // Will print gooseberry

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM