douxing6532
douxing6532
2016-10-18 12:14

在php中的特定键之后获取所有数组键

已采纳

I have an array like this,

$ptJson = {
    ["phoneSMS1"]=> "mobile",
    ["phoneSMS2"]=> "mobile",
    ["phoneSMS3"]=> "mobile",
    ["phoneSMS4"]=> "mobile",
    ["phoneSMS5"]=> "main"
}

And I have to delete the phoneSMS3, so I used unset to unset the key

unset($ptJson['phoneSMS3']);

It worked great.! Now I want to move rest keys level-up by one, but don't know how. Searched but have no luck.

So, how to find the rest array keys after phoneSMS3?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • doupin5408 doupin5408 5年前

    I'd iterate over the keys from the position you want to remove till the end of the array and assign the following key to the current position in each iteration:

    $prefix = 'phoneSMS';
    $index = 3;
    
    while (array_key_exists($prefix . ($index + 1), $ptJson)) {
        $ptJson[$prefix . $index] = $ptJson[$prefix . ($index + 1)];
        ++$index;
    }
    unset($ptJson[$prefix . $index]);
    
    点赞 9 评论 复制链接分享
  • dousikuai5417 dousikuai5417 5年前
    for($i = 2; $i < count($ptJson); $i++){
      $ptJson[$i] = 'phoneSMS'.($i+1);
    }
    

    this is how you can acess it you just should use it a bit more generic

    点赞 7 评论 复制链接分享
  • duanfangbunao36970 duanfangbunao36970 5年前
    $flg=0;
    $i=1;
    foreach($ptJson as $key=>$val){
        $i++;
        if($key =="phoneSMS3"){
            unlink($ptJson[$key]);
            $flg=1;
        }
        if($flg==1)
            $ptJson[$key]=$ptJson["phoneSMS".$i];
    }
    
    点赞 1 评论 复制链接分享
  • donglue8180 donglue8180 5年前

    I think reset($array) function may help.

    点赞 评论 复制链接分享

相关推荐