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 access sub array list gone wrong result and length

I have an PHP Array with Object with below sample:

Array
(
[0] => Array
    (
        [menuID] => 1
        [menuName] => AA
        [menuURL] => 
        [subMenu] => Array
            (
                [0] => Array
                    (
                        [subMenuID] => 1
                        [subMenuName] => Sub 1
                        [subMenuURL] => ab
                    )

                [1] => Array
                    (
                        [subMenuID] => 2
                        [subMenuName] => Sub 2
                        [subMenuURL] => ac
                    )

            )

    )

[1] => Array
    (
        [menuID] => 2
        [menuName] => AB
        [menuURL] => 
        [subMenu] => 
    )

)

Now I need to count and access array in subMenu but got strange value there.

I’m using this code:

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

foreach ($headerMenu as $list) {
    //print_r($list['menuName']);

    echo "<pre>";
    print_r(count($list['subMenu']));
}

It show me result 2 and 1. As you can see on the above sample array, it should show 2 for menu ID 1 and 0 for menu ID 2.

Is there any way how to solve it?

>Solution :

I’m not sure about the error, but i just change the syntax, and try it in wamp, and it did print 2 and 0.

<?php
$headerMenu = array(
    array(
        'menuID' => 1,
        'menuName' => 'AA',
        'menuURL' => '',
        'subMenu' => array(
            array(
                'subMenuID' => 1,
                'subMenuName' => 'Sub 1',
                'subMenuURL' => 'ab'
            ),
            array(
                'subMenuID' => 2,
                'subMenuName' => 'Sub 2',
                'subMenuURL' => 'ac'
            )
        )
    ),
    array(
        'menuID' => 2,
        'menuName' => 'AB',
        'menuURL' => '',
        'subMenu' => array()
    )
);

foreach ($headerMenu as $list) {
    echo "<pre>";
    print_r(count($list['subMenu']));
}
?>
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