是否可以从特定的索引值开始在数组元素中找到值的最后一次出现。我在这篇文章中找到了一个部分的解决方案[如何在多维array?](https://stackoverflow.com/questions/25046022/php-find-last-occurrence-from-multidimensional-array)中找到最后一项的关键,但它不允许从特定的索引开始。我正在循环通过一个数组匹配一个'id‘号。如果当前数组索引中不存在“id”号,我希望从那个点开始搜索该值的最后一次出现。
$last = "";
foreach($arr as $key => $array) {
if ( $array['id'] === $id) {
$last = $key;
}
}
echo $last."\n\n";发布于 2016-05-20 18:08:30
如果数组具有数字索引,则可以使用通常的for循环执行。
$last = false;
for($i = $start; $i >= 0; $i--) { // $start - index to start look up
if ( $arr[$i]['id'] === $id) {
$last = $i;
break; // if key is found, stop loop
}
}
if($last !== false)
echo $last."\n\n";
else
echo "Not found" . "\n";发布于 2016-05-20 18:00:25
<?php
$myArray = [
"bus" => "blue",
"car" => "red",
"shuttle" => "blue",
"bike" => "green";
];
$findValue = "blue";
$startIndex = "bus";
$continue = false;
$lastIndex = null;
foreach ($myArray as $key => $value)
{
if(!$continue && $key === $startIndex)
{
$continue = true;
} else if($continue) {
if($key === $findValue) {
$lastIndex = $key;
}
}
}基本上,我在这里所做的只是根据你想要找到的第一个索引来检查索引,如果它找到了这个索引,它会继续试着比较当前键的值和你想要指定的值。
https://stackoverflow.com/questions/37352944
复制相似问题