mysql 多维数组_从数据库结果生成多维数组的递归函数

我知道这个问题很老,但我面临着一个非常相似的问题-除了大量的数据。经过一番努力,我成功地在结果集的一次传递中构建了树-使用引用。这段代码不是很漂亮,但它工作得很快。它是非递归的,也就是说,只有一次通过结果集,然后是一次。array_filter最后:$dbh = new PDO(CONNECT_STRING, USERNAME, PASSWORD);$dbs = $dbh->query("SELECT n_id, n_parent_id from test_table order by n_parent_id, n_id");$elems = array();while(($row = $dbs->fetch(PDO::FETCH_ASSOC)) !== FALSE) {

$row['children'] = array();

$vn = "row" . $row['n_id'];

${$vn} = $row;

if(!is_null($row['n_parent_id'])) {

$vp = "parent" . $row['n_parent_id'];

if(isset($data[$row['n_parent_id']])) {

${$vp} = $data[$row['n_parent_id']];

}

else {

${$vp} = array('n_id' => $row['n_parent_id'], 'n_parent_id' => null, 'children' => array());

$data[$row['n_parent_id']] = &${$vp};

}

${$vp}['children'][] = &${$vn};

$data[$row['n_parent_id']] = ${$vp};

}

$data[$row['n_id']] = &${$vn};}$dbs->closeCursor();$result = array_filter($data, function($elem) { return is_null($elem['n_parent_id']); });print_r($result);

在此数据上执行时:mysql> select * from test_table;+------+-------------+| n_id | n_parent_id |+------+-------------+|    1 |        NULL ||    2 |        NULL ||    3 |           1 ||    4 |           1 ||    5 |           2 ||    6 |           2 ||    7 |           5 ||    8 |           5 |+------+-------------+

最后一次print_r产生这个输出:Array(

[1] => Array

(

[n_id] => 1

[n_parent_id] =>

[children] => Array

(

[3] => Array

(

[n_id] => 3

[n_parent_id] => 1

[children] => Array

(

)

)

[4] => Array

(

[n_id] => 4

[n_parent_id] => 1

[children] => Array

(

)

)

)

)

[2] => Array

(

[n_id] => 2

[n_parent_id] =>

[children] => Array

(

[5] => Array

(

[n_id] => 5

[n_parent_id] => 2

[children] => Array

(

[7] => Array

(

[n_id] => 7

[n_parent_id] => 5

[children] => Array

(

)

)

[8] => Array

(

[n_id] => 8

[n_parent_id] => 5

[children] => Array

(

)

)

)

)

[6] => Array

(

[n_id] => 6

[n_parent_id] => 2

[children] => Array

(

)

)

)

))

这正是我要找的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值