Томица Кораћ
Томица Кораћ

Reputation: 2672

PHP - Convert multidimensional associative array's key strings into numbers

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.

Upvotes: 3

Views: 6449

Answers (2)

Cameron Martin
Cameron Martin

Reputation: 6012

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.

Upvotes: 9

blockhead
blockhead

Reputation: 9705

You can use array_values for that.

Upvotes: 0

Related Questions