0

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...

4
  • there is no $data['variables'][0], if you don't know the keys then you need to do a loop inside a loop, if you already know the keys you don't Commented Jun 10, 2014 at 23:30
  • Seeing as the key is stored in $k, why can I not use: $data['variables'][$key]['name'] Commented Jun 10, 2014 at 23:32
  • thats the key for the outer array Commented Jun 10, 2014 at 23:32
  • FYI: multiple foreach loops for a multidimensional array is very common Commented Jun 10, 2014 at 23:33

2 Answers 2

2

You can do

foreach ($data['variables'] as $k => $v) {
  $name = $v['name'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

well if i knew that was what you where asking ... :-)
1

You can also try this

create a new array containing just the names..

$new_arr = array_column($data['variables'],'name' );
echo $new_arr[0].'<br/>';
echo $new_arr[1].'<br/>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.