Reindex array by increasing and decreasing all of top indexes

独自空忆成欢 提交于 2019-12-12 04:07:43

问题


First, I have to list what I have found

How to Remove Array Element and Then Re-Index Array?

PHP reindex array?

They did not make sense in my case. I have fallen into ridiculous request and I've force to find the way out, then please don't ask me why I want to do that.

I have below array

$input = array(
          0=>array('a', 'b'=>array('c')),
          1=>array('b', 'c'=>array('d')),
          2=>array('c', 'd'=>array('e')),
        );

I want to increase all of keys by 1 or decrease by 1 (acceptable to index is negative int number)

Here is expected result

//after increased by 1
$input = array(
          1=>array('a', 'b'=>array('c')),
          2=>array('b', 'c'=>array('d')),
          3=>array('c', 'd'=>array('e')),
        );

or

//after decreased by 1
$input = array(
          -1=>array('a', 'b'=>array('c')),
          0=>array('b', 'c'=>array('d')),
          1=>array('c', 'd'=>array('e')),
        );

The closet answer I got here from raina77ow in the question How to increase by 1 all keys in an array?

$arr = array_flip(array_map(function($el){ return $el + 1; }, array_flip($arr)));

But it just works with simple array key pairs, if array value is other array instead of a string or integer, it would raise the exception

array_flip(): Can only flip STRING and INTEGER values!

The thing what I could think is handling the array to swap roster manually, it would be the final way if there were not any other workaround.

Any help is appreciated!


回答1:


The easiest way would probably to use foreach and make a new array... like this:

$new = array();
foreach($arr as $k=>$v) {
    $new[$k+1] = $v; // either increase
    $new[$k-1] = $v; // or decrease
}

You can also perform the operation by passing the original array by reference.




回答2:


This should so the trick.

    // Increase by one
    $input = array_combine(
        array_map(function($value) {
            return $value += 1;
        }, array_keys($input)), $input
    );


来源:https://stackoverflow.com/questions/18393644/reindex-array-by-increasing-and-decreasing-all-of-top-indexes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!