无法访问php中的嵌套数组
我有一个这样的数组我想这样访问这个子类别数组无法访问php中的嵌套数组,php,arrays,foreach,Php,Arrays,Foreach,我有一个这样的数组我想这样访问这个子类别数组 foreach($data as $parent_category){ $ndata=$parent_category['subCategory']; foreach ($ndata as $subCategory){ } } 其中,$data是我的主数组print\r$data给出这个输出 当我访问这个数组时,我得到一个未定义索引的错误:subCategory 请帮帮我 数组键5没有子类别索引 数组中的第一个
foreach($data as $parent_category){
$ndata=$parent_category['subCategory'];
foreach ($ndata as $subCategory){
}
}
其中,$data是我的主数组print\r$data给出这个输出
当我访问这个数组时,我得到一个未定义索引的错误:subCategory
请帮帮我
数组键5没有子类别索引 数组中的第一个条目就可以了 您可以使用array\u key\u exists函数检查子类别是否存在 如你所见,这里:
[5] => Array
(
[name] => ABC CULTURE
)
数组不包含具有索引子类别的元素。因此,只需通过调用以下命令检查索引是否存在:
...
if (isset($parent_category['subCategory'])) {
...
具有键5的项不包含子类别键。要避免出现警告,请尝试使用:
foreach($data as $parent_category){
if (isset($parent_category['subCategory'])) {
$ndata = $parent_category['subCategory'];
foreach ($ndata as $subCategory){
}
}
}
按如下所示修改代码,所以对于没有子类别的情况,不会得到未定义的索引
foreach($data as $parent_category){
$ndata=isset($parent_category['subCategory'])?$parent_category['subCategory']:'';
if(!empty($ndata)){
foreach ($ndata as $subCategory){
}
}
}
这是整个阵列吗?因为数组中只有第一项有子类别,而另一项只有名称,因此是未定义的索引
foreach($data as $parent_category){
$ndata=isset($parent_category['subCategory'])?$parent_category['subCategory']:'';
if(!empty($ndata)){
foreach ($ndata as $subCategory){
}
}
}