在阵列和PHP是否存在搜索增量,否则退出和返回值 [英] PHP search in array and if exists increment, else exit and return value

查看:145
本文介绍了在阵列和PHP是否存在搜索增量,否则退出和返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种类型的数组:

 阵列

    [0] => 001
    [1] => 002
    [2] => 003
    [3] => 222
    [4] => 0002
    [5] => 0003
    [6] => 0004
    [7] => 1000
    [8] => 2000
    [9] => 3000

和我需要检查,如果一个值,创造飞由code本身的存在与否。如果没有,用它,否则增加的1,并再次检查(的几个原因,我不能选择的最大数量只增加1的)。

所以,我没有写这个片段,但我认为它永远不会从循环退出,我不知道怎么又来了(再次)重新检查...

  $ base_test = 001;
而(array_key_exists($ base_test,$ array_start))
{
     $ base_test ++;
     //我怎么能现在重新检查这个新的价值?
}


解决方案

使用的递归函数的像下面的

 函数checkArray($ VAL){
    $ ARR =阵列
    (
        0 => 001,
        1 => 002,
        2 => 003,
        3 => 222,
        4 => 0002,
        5 => 0003
        6 => 0004,
        7 => 1000,
        8 => 2000年,
        9 => 3000,
    );    如果(in_array($ VAL,$ ARR)){
      $ VAL ++;
      checkArray($ VAL);
    }
      返回$ VAL;
}回声checkArray(222);

I have this type of array:

Array
(
    [0] => 001
    [1] => 002
    [2] => 003
    [3] => 222
    [4] => 0002
    [5] => 0003
    [6] => 0004
    [7] => 1000
    [8] => 2000
    [9] => 3000
)

And I need to check if a value, "created" on the fly by code itself, exists or not. If not, use it, else increments it of 1 and check again (for several reasons, I cannot pick the biggest number and simply add "1").

So, I did write this snippet, but I think that it never will exit from cycle and I don't know how re-check again (and again)...

$base_test = 001;
while (array_key_exists($base_test, $array_start))
{
     $base_test++;
     // how can I now re-check for this new value?
}

解决方案

Use a recursive function like the following

function checkArray($val){
    $arr = array
    (
        0 => 001,
        1 => 002,
        2 => 003,
        3 => 222,
        4 => 0002,
        5 => 0003,
        6 => 0004,
        7 => 1000,
        8 => 2000,
        9 => 3000,
    );

    if(in_array($val ,$arr )){
      $val++;
      checkArray($val);
    }
      return $val;
}

echo checkArray(222);

这篇关于在阵列和PHP是否存在搜索增量,否则退出和返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆