通过多维数组在PHP中获取类别级别可以通过以下步骤实现:
$categories = array(
array(
'name' => '电子产品',
'level' => 1,
'subcategories' => array(
array(
'name' => '手机',
'level' => 2,
'subcategories' => array(
array(
'name' => '智能手机',
'level' => 3,
'subcategories' => array()
),
array(
'name' => '功能手机',
'level' => 3,
'subcategories' => array()
)
)
),
array(
'name' => '电脑',
'level' => 2,
'subcategories' => array(
array(
'name' => '笔记本电脑',
'level' => 3,
'subcategories' => array()
),
array(
'name' => '台式电脑',
'level' => 3,
'subcategories' => array()
)
)
)
)
),
array(
'name' => '服装',
'level' => 1,
'subcategories' => array(
array(
'name' => '男装',
'level' => 2,
'subcategories' => array()
),
array(
'name' => '女装',
'level' => 2,
'subcategories' => array()
)
)
)
);
function getCategoryLevel($categories, $targetCategory) {
foreach ($categories as $category) {
if ($category['name'] == $targetCategory) {
return $category['level'];
} elseif (!empty($category['subcategories'])) {
$subCategoryLevel = getCategoryLevel($category['subcategories'], $targetCategory);
if ($subCategoryLevel !== false) {
return $subCategoryLevel;
}
}
}
return false;
}
$targetCategory = '笔记本电脑';
$categoryLevel = getCategoryLevel($categories, $targetCategory);
if ($categoryLevel !== false) {
echo "类别 '$targetCategory' 的级别为 $categoryLevel";
} else {
echo "未找到类别 '$targetCategory'";
}
以上代码将输出:类别 '笔记本电脑' 的级别为 3。
对于以上问题,腾讯云没有直接相关的产品和产品介绍链接地址。
领取专属 10元无门槛券
手把手带您无忧上云