如何找到两个数组项之间的所有值(包括开始值和结束值)?
示例:
public function addError($attribute, $error = '') {
$renamed_attr = $this->renamedFields($attribute);
parent::addError($renamed_attr, $error);
}
输入:array('3X' => '3X','EX'=> 'EX','VG'=>'VG','G'=>'G','F'=>'F','P'=>'P')
,$arr
,'EX'
输出:'F'
提前致谢..
答案 0 :(得分:0)
尝试:
$arr = array('3X' => '3X','EX'=> 'EX','VG'=>'VG','G'=>'G','F'=>'F','P'=>'P');
function findValuesBetweenTwoItems($arr, $start, $end) {
$result = [];
$has_started = false;
foreach ( $arr as $item->$value ) {
if( ( $item != $end && $has_started ) || $item == $start) {
array_push($result, $value);
$has_started = true;
}
if( $item == $end ) {
array_push($result, $value);
return $result;
}
}
$my_values = findValuesBetweenTwoItems($arr, 'EX', 'F');
var_dump($my_values);
答案 1 :(得分:0)
$array = array('3X' => '3X','EX'=> 'EX','VG'=>'VG','G'=>'G','F'=>'F','P'=>'P');
$start = "3X";
$end ="F";
$new_array = [];
$i=0;$go=false;
foreach ($array as $element) {
if($go){
$new_array[$i] = $element;
$i++;
}
if($element==$start){
$go = true;
}
if($element==$end){
$go = false;
}
}
$total_elems_new = count($new_array);
unset($new_array[$total_elems_new-1]);
print_r($new_array);
在PHP 5.6上测试
答案 2 :(得分:0)
试试这个:
$array = array('3X' => '3X','EX'=> 'EX','VG'=>'VG','G'=>'G','F'=>'F','P'=>'P');
$arrayKeys = array_keys($array);
$input1 = '3X';
$input2 = 'F';
if(in_array($input1,$array) && in_array($input2,$array)) {
if (array_search($input1, array_keys($array)) >= 0) {
if (array_search($input2, array_keys($array)) >= 0) {
if (array_search($input1, array_keys($array)) < array_search($input2, array_keys($array))) {
echo "Keys in between: ";
for ($i = array_search($input1, array_keys($array)); $i <= array_search($input2, array_keys($array)); $i++) {
echo $array[$arrayKeys[$i]] . ", ";
}
} else {
echo "Keys in between: ";
for ($i = array_search($input2, array_keys($array)); $i <= array_search($input1, array_keys($array)); $i++) {
echo $array[$arrayKeys[$i]] . ", ";
}
}
} else {
echo "Value not found!";
}
} else {
echo "Value not found!";
}
} else{
echo "Value not found!";
}
答案 3 :(得分:0)
$from = 'EX';
$to = 'F';
$result = null;
$state = 0;
foreach ($a as $k => $v) {
if (($state == 0 && $from === $v) || ($state == 1 && $to === $v))
$state++;
if ($state && $state < 3)
$result[$k] = $v;
elseif ($state >= 2)
break;
}
if ($state != 2)
$result = null;
如果$from
为$state
(初始值),则循环搜索第一次出现的0
,如果$to
,则首次出现$state
是1
。对于$state
的其他值,循环停止处理。
当找到$from
或$to
时,$state
会递增。这些值存储在$result
$state is either
1 (
$ is found), or
2 (
$ to`中。{/ p>
因此,$state == 2
表示找到了两个值,$result
包含$a
和$from
之间$to
数组的值。否则,$result
被分配到null
。