在多维数组中保持计数键

时间:2015-04-12 16:44:31

标签: php arrays

我有关联多维数组

Array
(
[1] => Array
    (
        [Chapter] => Name 1
        [Section] => Array
            (
                [1] => Section name 1
                [2] => Section name 2
                [3] => Section name 3
            )
    )

[2] => Array
    (
        [Chapter] => Name 2
        [Section] => Array
            (
                [1] => Section name 4
                [2] => Section name 5
            )
    )
)

我想继续计算部分名称1,部分名称2,部分名称3,部分名称4,部分名称5的键编号。数组的键将与部分名称匹配 所以它看起来像这样

    Array
(
[1] => Array
    (
        [Chapter] => Name 1
        [Section] => Array
            (
                [1] => Section name 1
                [2] => Section name 2
                [3] => Section name 3
            )

    )

[2] => Array
    (
        [Chapter] => Name 2
        [Section] => Array
            (
                [4] => Section name 4
                [5] => Section name 5
            )
    )
)

我正在尝试

$count = 0;
foreach ($sections as $key => $value) {
    foreach ($value['Section'] as $k => $val) {
        $count ++;
        $value['Section'][$count] = $value['Section'][$k];
        unset($value['Section'][$k]);
    }
}

但它仍然从1开始计算每个数组。

1 个答案:

答案 0 :(得分:1)

试试这个

$count = 0;
foreach ($sections as $key => $value) {
    $newSection = array();
    foreach ($value['Section'] as $k => $val) {
        $count++;
        $newSection[$count] = $val;
    }
    $sections[$key]['Section'] = $newSection;
}

如果您使用&$value,那么您的第一部分将为空,因为您将unset

因此,使用正确的密钥并在Section foreach loop覆盖部分值后,将您的部分名称添加到新数组中。

用于解释传递为参考

$count = 0;
// Pass $value as reference
foreach ($sections as $key => &$value) {
    $newSection = array();
    foreach ($value['Section'] as $k => $val) {
        $count++;
        $newSection[$count] = $val;
    }

    // Overwrite reference "Section"
    // This will manipulate $sections array
    $value['Section'] = $newSection;

    // Without reference, overwrite $sections array
    $sections[$key]['Section'] = $newSection;
}