douxing6532 2016-10-18 12:14
浏览 123
已采纳

在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 2016-10-18 12:27
    关注

    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]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?