Thursday, 30 August 2018

PHP - Converts multidimensional associative array 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.

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.

0 comments:

Post a Comment