Ryan Palmer
Ryan Palmer

Reputation: 543

Get integer value/position for keys in the sub array of a multi-dimensional array

I have multi-dimensional array where I'm trying to output an integer value for the keys in the second array (sub array).

My array is pretty basic, like this:

$array = array(
    array(
        'a' => 'd',
        'b' => 'e',
        'c' => 'f'
    ),
    array(
        'a' => 'x',
        'b' => 'y',
        'c' => 'z'
    ),
);

So when I create a foreach for that array...

foreach ( $array as $array_key => $sub_array ) {
    foreach ( $sub_array as $key => $value ) {
        echo $key;
    }
}

I output $key in the sub-loop and that just returns the array's key values, which are a, b, c - a, b, c

How can I actually get the integer value or position of those key values in the sub-array? So for each grouping in the array, a would be 1, b would be 2, c would be 3. Then it would start over for the next grouping in the array.

I've tried using $int++; but that applies to both groups in the array, resulting in it going from 1-6, instead of 1-3, 1-3, etc.

Could something with array_keys work on this? Any help, as always, would be hugely appreciated!

Upvotes: 0

Views: 628

Answers (1)

Jaime Gris
Jaime Gris

Reputation: 1126

Try this code.

foreach ( $array as $array_key => $sub_array ) {
    $i = 1;
    foreach ( $sub_array as $key => $value ) {
        echo $i . ' - ' $key . '   ';
        $i++;
    }
}

This will give you an expected result.

1 - a  2 - b   3 - c  1 - a  2 - b   3 - c

And if you use the this code below.

$i = 1;
foreach ( $array as $array_key => $sub_array ) {
    foreach ( $sub_array as $key => $value ) {
        echo $i . ' - ' $key . '   ';
        $i++;
    }
}

This is the result.

1 - a  2 - b   3 - c  4 - a  5 - b   6 - c

Which is the output you encountered, not you expect. Note the location of the variable $i.

Upvotes: 3

Related Questions