I need help
I need help

Reputation: 13

php re-index numeric keys in associative array with combined numeric and string keys

I have this array

 [20_fill_1] => Array
    (
        [autoTuned] => Array
            (
                [0] => fill-0*6.35*6.6*legitPhraseWith*VMWshkqbhfA*fill_3.mp4
            )

        [fill] => Array
            (
                [0] => fill-0*6.35*6.6*subwordPhraseWith*VMWshkqbhfA*fill_4.mp4
            )

        [1] => fill-0*6.35*6.6*legitPhraseWith*VMWshkqbhfA*fill_3.mp4
        [ill] => Array
            (
                [oil] => Array
                    (
                        [0] => oil-0*6.8*7.05*similarSubwordPhraseWith*HZNbg-1bz1c*oil_4.mp4
                    )

            )

    )

The reason there is no [0] is because I just unset it. Now I want that [1] to become the new [0], and if there were more numeric keys, i'd want them to also change so the numeric keys are in order. However, I need to keep the string keys.

Edit:this was the array before I removed the zeroth element:

[20_fill_1] => Array
    (
        [0] => added#fill-0*6.35*6.6*subwordPhraseWith*VMWshkqbhfA*fill_4.mp4
        [autoTuned] => Array
            (
                [0] => fill-0*6.35*6.6*legitPhraseWith*VMWshkqbhfA*fill_3.mp4
            )

        [fill] => Array
            (
                [0] => fill-0*6.35*6.6*subwordPhraseWith*VMWshkqbhfA*fill_4.mp4
            )

        [1] => fill-0*6.35*6.6*legitPhraseWith*VMWshkqbhfA*fill_3.mp4
        [ill] => Array
            (
                [oil] => Array
                    (
                        [0] => oil-0*6.8*7.05*similarSubwordPhraseWith*HZNbg-1bz1c*oil_4.mp4
                    )

            )

    )

Upvotes: 1

Views: 346

Answers (2)

BeetleJuice
BeetleJuice

Reputation: 40926

If your array isn't very large, you could build another array:

$output = [];

foreach ($original as $key => $item):
  if(is_string($key)) $output[$key] = $item;
  else $output[] = $item;
endforeach;

$output is what you want.

Update:

You could also unshift (insert) a dummy element at the start of the array, then shift (remove) it. This will re-key the numerical keys and leave the string keys alone:

array_unshift($original,'dummy');
array_shift($original);

thanks to @brennonbrimhall for the inspiration.

Upvotes: 1

brennonbrimhall
brennonbrimhall

Reputation: 54

Rather than unset the 0th element, consider using array_shift. It will automatically remove the 0th element, reindex other numerical indices, and preserve non-numerical keys and values.

Upvotes: 0

Related Questions