3

I have a multidimensional associative array like this:

$type = Array(
  [unit-1] = Array(
    [taxon-1] = Array(
      [0] = Array(
        [a] = 1,
        [b] = 1,
        [c] = 'string1'
      ),
      [1] = Array(
        [a] = 1,
        [b] = 1,
        [c] = 'string2'
      ),
    ),
    [taxon-2] = Array(
      [0] = Array(
        [a] = 1,
        [b] = 2,
        [c] = 'string3'
      ),
      [1] = Array(
        [a] = 1,
        [b] = 2,
        [c] = 'string4'
      ),
    ),
  [unit-2] = Array(
    [taxon-1] = Array(
      [0] = Array(
        [a] = 2,
        [b] = 1,
        [c] = 'string5'
      ),
      [1] = Array(
        [a] = 2,
        [b] = 1,
        [c] = 'string6'
      ),
    ),
    [taxon-2] = Array(
      [0] = Array(
        [a] = 2,
        [b] = 2,
        [c] = 'string7'
      ),
      [1] = Array(
        [a] = 2,
        [b] = 2,
        [c] = 'string8'
      ),
    ),
  )

How do I convert all the associative keys (unit-1, unit-2... and taxon-1, taxon-2...) into ordinals (0, 1... and 0, 1...). Do I need to use a foreach loop, and if yes, how would it go?

Please note that there is not a finite number of units and taxons in the array.

2 Answers 2

9

If there's definitely two levels:

$type = array_values(array_map('array_values', $type));

To re-index all array keys from an array:

function array_reindex($array) {
    if(is_array($array)) {
        return array_map('array_reindex', array_values($array));
    } else {
        return $array;
    }
}

Haven't tested it but it should work.

Sign up to request clarification or add additional context in comments.

2 Comments

Splendid. This worked like a charm. Thanks a lot. Yes, for now I only need two levels. Just wondering though, how much more complicated would it be if there were more levels?
Updated my answer with a function to recursively re-index an array.
0

You can use array_values for that.

1 Comment

Indeed I can, and it would work perfectly, but only for the first level of keys, i.e. unit-1, unit-2... Taxon keys would not be changed. How can I utilize array_values to apply recursively deeper into the array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.