【问题标题】:I want to get an array on all the parent ids of an id我想在一个 id 的所有父 id 上获取一个数组
【发布时间】:2016-01-26 20:15:31
【问题描述】:

我有一个有 3 列的表。 id, parent_id and text。我想要一个返回所有parent idid 的函数..

假设我传递了一个参数4,即ID,数组应该返回4,3,2,1,因为3是4的父级,2是3的父级,同样,1是2的父级。 我怎样才能做到这一点?

到目前为止,我已经尝试过了。但这是返回数组..

function getTree($id){
    $arr = array();
    $parent = mysql_query("SELECT parent_id FROM task WHERE id = '".$id."'");
    $parent_query = mysql_fetch_assoc($parent);
    if ($parent_query['parent_id']==0){
        echo "This is the parent";
    } else {
        $arr[] = $id;
        $arr[] = $parent_query['parent_id'];
        $arr[] = getTopTree($parent_query['parent_id']);
        echo '<pre>';
      print_r($arr);
      echo '</pre>';
    }
}

【问题讨论】:

  • 嗨,只是好奇,但你读过this 了吗?
  • 到目前为止你尝试过什么?
  • 你能说得清楚一点吗?我
  • 你听说过递归吗?

标签: php mysql loops


【解决方案1】:

您可以像 as 一样创建自己的自定义函数

function checkParentIds($id, $data = array()) {
    $parent = mysql_query("SELECT parent_id FROM task WHERE id = '$id'");
    $parent_query = mysql_fetch_assoc($parent);
    if ($parent_query['parent_id'] > 0) {
        $data[] = $parent_query['parent_id'];
        checkParentIds($parent_query['parent_id'], $data);
    } else {
        $parent_result = (empty($data)) ? 1 : implode("','", $data);
    }
    return $parent_result;
}

【讨论】:

  • 完美运行。就一件事。我希望 id 本身成为字符串的一部分。我该怎么做?
  • 如果我将4 传递为id,我应该得到4,3,2,1 而不是3,2,1
  • 在 if 条件之前只需使用 $data[] = $id;
  • 我使用了这段代码,但它返回了10,5,4,3,2,1,1。 1 在最后重复两次。
【解决方案2】:
select id, group_concat(parent_id) as parents, test <yourtable> group by id;

然后在 php 中,您可以展开检索到的行的适当列:

// ... retrieving all the rows stuff
$parentsIds = explode(',', $row['parents']);

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2020-11-02
    • 1970-01-01
    • 2021-01-01
    相关资源
    最近更新 更多