Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Array – Fetch all sub values

Im trying to fetch all [labels] along with its [id] from the below array.

Array
(
    [0] => Array
        (
            [elements] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [label] => This is a Page 1 Question 1
                        )
                    [1] => Array
                        (
                            [id] => 4
                            [label] => This is a Page 1 Question 2
                        )
                )
        )

    [1] => Array
        (
            [elements] => Array
                (
                    [0] => Array
                        (
                            [id] => 10
                            [label] => This is a Page 2 Question 1
                        )
                    [1] => Array
                        (
                            [id] => 13
                            [label] => This is a Page 2 Question 2                          
                        )
                )
        )

    [2] => Array
        (
            [elements] => Array
                (
                    [0] => Array
                        (
                            [id] => 18
                            [label] => This is a Page 3 Question 1                           
                        )
                    [1] => Array
                        (
                            [id] => 21
                            [label] => This is a Page 3 Question 2                           
                        )
                )
        )
)

I did some research and tried using the below code, but it return something else.

foreach($elements as $key => $value) {
     echo $value['label'];
     echo $value['id'];
    }

Kindly help me out.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With such structure of array you should iterate twice:

foreach ($elements as $key => $value) {
    foreach ($value['elements'] as $element) {
        echo $element['label'];
        echo $element['id'];
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading