Question

I have an array like them i would like to access this sub category array like this

foreach($data as $parent_category){
        $ndata=$parent_category['subCategory'];
        foreach ($ndata as $subCategory){

 }
}

Where $data is my main array print_r($data) give this output

When i access this array i got an error Undefined index: subCategory

Help me please ...

Array (
[1] => Array
    (
        [name] => Indian Culture
        [subCategory] => Array
            (
                [0] => Array
                    (
                        [name] => Indain Culture-1
                        [articleId] => 10
                    )

                [1] => Array
                    (
                        [name] => culture -1 
                        [articleId] => 22
                    )

            )

    )

[5] => Array
    (
        [name] => ABC CULTURE
    )

)

Was it helpful?

Solution

As You see, here:

[5] => Array
(
    [name] => ABC CULTURE
)

Your array does not contain element with index "subCategory". So just check, that the index is present by invoking:

...
if (isset($parent_category['subCategory'])) {
...

OTHER TIPS

Array key 5 doesn't have a subCategory index.

The first entry in the array will be fine.

You can check if subCategory is present using the array_key_exists function.

http://uk1.php.net/array_key_exists

Difference between isset and array_key_exists

Item with key 5 does not contain subCategory key. To avoid warnings, try with:

foreach($data as $parent_category){
    if (isset($parent_category['subCategory'])) {
        $ndata = $parent_category['subCategory'];
        foreach ($ndata as $subCategory){

        }
    }
}

Modified your code as below, so you will not get undefined index for those cases where you didn't have subcategory.

foreach($data as $parent_category){
    $ndata=isset($parent_category['subCategory'])?$parent_category['subCategory']:'';
    if(!empty($ndata)){
      foreach ($ndata as $subCategory){

      }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top