Home > OS >  PHP Array - Fetch all sub values
PHP Array - Fetch all sub values

Time:12-12

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.

CodePudding user response:

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'];
    }
}
  • Related