【问题标题】:Selected Category value in Dropdown from Category Tree从类别树的下拉列表中选择的类别值
【发布时间】:2016-08-31 09:22:31
【问题描述】:

这是我创建 n 级类别的代码。

function fetchCategoryTree($parent = 0, $spacing = '', $user_tree_array = '') {

    if (!is_array($user_tree_array))
        $user_tree_array = array();

    $sql = "SELECT `cat_id`, `cat_name`, `parent_id` FROM `category` WHERE  `parent_id` = $parent  ORDER BY cat_id ASC";
    $query = mysql_query($sql);
    if (mysql_num_rows($query) > 0) {
        while ($row = mysql_fetch_object($query)) {
            $user_tree_array[] = array("id" => $row->cat_id, "name" => $spacing . $row->cat_name);
            $user_tree_array = fetchCategoryTree($row->cat_id, $spacing . ' -', $user_tree_array );
        }
    }
    return $user_tree_array;
}

$categoryList = fetchCategoryTree();

在下拉列表中显示所有类别

$id=$_GET['id'];
<td> Category:</td><td><select name="parentcat" id="parentcat" onchange="getText(this)">

    <option selected value="Root">--Root Level--</option>
        <?php
     foreach($categoryList as $cl) {
         ?>
         <option value="<?php echo $cl["id"] ?>"><?php echo $cl["name"]; ?></option>
     <?php }  ?>

现在我想在下拉列表中显示选定的父名称。如果类别名称为Laptop,则其父名称为'Electronics。我希望电子产品出现在下拉列表中。

我的数据库是这样的:

cat_id |猫名 | parent_id ------------------------------------------- 1 |电子产品| 0 ------------------------------------------- 2 |笔记本电脑 | 1

如果我选择Laptops,我想要这个Electronics 在下拉列表中。

【问题讨论】:

  • 我们如何确定笔记本电脑的父母是电子产品?

标签: php


【解决方案1】:

你怎么知道在哪里被选中? $_GET['id']

的示例
function searchForId($id, $array) {
   foreach ($array as $key => $val) {
     if ($val['id'] === $id) {
       return true;
     }
   }
   return null;
}

$selected_id = (int)$_GET['id'];
?>
<option <?=(searchForId($selected_id,$categoryList))?'selected':''?> value="Root">--Root Level--</option>
<?php
foreach($categoryList as $cl) {
?>
   <option value="<?php echo $cl["id"] ?>"><?php echo $cl["name"]; ?></option>
<?php }  ?>

【讨论】:

  • 是的,我从中获得了价值:$id=$_GET['id];
  • 好的,那就试试我的例子:)
  • 对不起,但它不起作用,它给了我所有的下拉结果
  • 我已经更改了多维数组搜索的代码!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
相关资源
最近更新 更多