PHP增量数组键+1

时间:2016-09-05 23:31:35

标签: php arrays increment

我正在寻找一些简单的解决方案(1行)来增加多数组中的所有键+1。

    Array (
       0 => Array (
                   7 => 'foo',
                   13 => 'foo'
                  ),
       1 =>  Array (
                   2 => 'foo',
                   25 => 'foo'
                  ),
       4 =>  Array (
                   24 => 'foo'
                  )
)

结果阵列

    Array (
       1 => Array (
                   8 => 'foo',
                   14 => 'foo'
                  ),
       2 =>  Array (
                   3 => 'foo',
                   26 => 'foo'
                  ),
       5 =>  Array (
                   25 => 'foo'
                  )
)

2 个答案:

答案 0 :(得分:1)

$data = [
       0 => [7 => 'foo', 13 => 'foo'],
       1 => [2 => 'foo', 25 => 'foo'],
       4 => [24 => 'foo'],
];

// top level
$data = array_combine(
    array_map(function ($key) { return ++$key; }, array_keys($data)),
    $data
);
// then the elements (use array_walk_recursive() if you have more levels)
array_walk(
    $data,
    function(&$data) {
        $data = array_combine(
            array_map(function ($key) { return ++$key; }, array_keys($data)),
            $data
        );
    }
);
var_dump($data);

Demo

答案 1 :(得分:0)

我不确定单线程,特别是因为你有一个多维数组。但是,我就是这样做的。老实说,无论如何,所有的单线优雅都会让事情变得更加复杂。在我的拙见中,最好使用可读代码。

// Example array
$array = array (
      0 => array (
            7 => 'foo',
            13 => 'foo'
      ),
      1 =>  array (
            2 => 'foo',
            25 => 'foo'
      ),
      4 =>  array (
            24 => 'foo'
      )
);

// My solution to increment each key and nested key
$new = array();
foreach($array as $key => $value) {
      foreach($value as $inkey => $inval) {
            $value[$inkey+1] = $inval;
            unset($value[$inkey]);
      }
      $new[$key+1] = $value;
}
$array = $new;

// Display the array
echo '<pre>'; print_r($array); echo '<pre/>';