Tomulent Tomulent - 7 months ago 23
PHP Question

Iterate through multidimensional associative array in PHP when every key is a string

I've got an array like:

$fruits = array(
'citrus' => array(
'fruit one' => 'orange',
'fruit two' => 'lime',
),
'melon' => array(
'fruit one' => 'honeydew',
'fruit two' => 'cantalope',
),
'berry' => array(
'fruit one' => 'raspberry',
'fruit two' => 'strawberry',
),
'apple' => array(
'fruit one' => 'granny smith',
'fruit two' => 'fuji',
)

);


I want to be able to access slices of it, like
echo $fruits[0]['fruit one'];
so that I can create a for loop to get at specific groups of the array. By that I mean, I would ideally be able to do something like:

for($i = 0; $i <= 1; $i++)
echo $fruit[$i]['fruit one'];

// Then some other code

for($i = 2; $i <= 3; $i++)
echo $fruit[$i]['fruit one'];


Of course I can't do that since every key is a string. Is there a simple solution to this or did I just code this dumbly?

Edit: I made the array longer to fully demonstrate what I'm trying to do.

Answer
function replaceKeys(&$array)
{
    $i = 0;
    $ptr = null;
    foreach ($array as $values) {
        $ptr[$i] = $values;
        $i++;
    }
    $array = $ptr;
}

$fruits = array(
  'citrus' => array(
    'fruit one' => 'orange',
    'fruit two' => 'lime',
  ),
  'melon' => array(
    'fruit one' => 'honeydew',
    'fruit two' => 'cantalope',
  )
);


replaceKeys($fruits);

var_dump($fruits[0]['fruit one']);

//Output: orange