user45669 user45669 - 4 months ago 8
PHP Question

Keep counting keys in multidemensional array

I have the associative multidemensional array

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
)
)
)


I would like to continue counting for keys numbers for Section name 1, Section name 2, Section name 3, Section name 4, Section name 5. Keys of array will match section name
So it will looks like this

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
)
)
)


I was trying to do

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


but it still count each array from 1.

Answer

Try this

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

If you use &$value, then your first section will be empty, since you will unset them.

So add your section name to new array with correct key and after Section foreach loop overwrite section value.

For explaining passing as reference

$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;
}