Search code examples
phparraysmultidimensional-arraykeykey-value

Access multidimensional array without multiple loops


Let's say I have an array formatted like so:

   $data = array(
        'variables' => array(
            '823h9fhs9df38h4f8h' => array(
                'name' => 'Foo',
                'value' => 'green'
            ),
            'sdfj93248fhfhf88rh' => array(
                'name' => 'Bar',
                'value' => 'red'
            )
        )
    );

Say I wanted to access the name & values of each array in the variables array. Surely you can access it just looping over the main variables array and not looping over each individual item array? Something like so?

foreach ($data as $k => $v) {
    $name = $data['variables'][0]['name'];
}

I'm sure I'm missing something simple...


Solution

  • You can do

    foreach ($data['variables'] as $k => $v) {
      $name = $v['name'];
    }