0

我有一个存储帐户和订阅的数据库。一个帐户可以包含帐户和订阅,并具有三个以上的父级别。

数据库查询结果中的一行如下所示:

$array = (0 => array("level" => "2", "accountno" => "123124234", "accountname" => "Hansel", "parentaccountno" => "000213123", "subscription" => "5423213213", "username" => "Gretchen");

(级别 1 表示它是顶级的,它的 PARENTACCOUNTNO = null)。

从这里我试图创建一个看起来像这样的多维数组:

accounts:
    000213123
        accounts:
            123124234
                name: Hansel
                subscriptions:
                    5423213213
                        username: Gretchen

这是我到目前为止的代码,它在前两个级别上运行得非常好。当存在三个或更多级别时,事情变得更加复杂,因为每个帐户只知道自己的父级:

$hierarchy = array();

foreach ($decode as $row) {
    $accountno = $row["ACCOUNTNO"];
    $msisdn = $row["MSISDN"];
    if ($row["PARENTACCOUNTNO"] == null)
        $base_array_key = $hierarchy["accounts"];

    $base_array_key[$accountno] = array("name" => $row["ACCOUNTNAME"], "accounts" => array(), "subscriptions" => array());

    $hierarchy["accounts"][$accountno]["accounts"]["321323123213"] = "blaha";

    if ($row["MSISDN"] != null)
        $hierarchy["accounts"][$accountno]["subscriptions"][$msisdn] = array("enduser" => $row["ENDUSER"]);
}

我现在想到的解决方案是将基键从每次迭代传递到下一次迭代,然后如果例如上一个级别比这个级别高两个级别,只需使用某种字符串替换来删除最后两个部分钥匙。

有更好的想法吗?我很确定这是一种糟糕的方式来做我想要完成的事情。

4

3 回答 3

0

创建一个临时关联数组:

$all_records = array();

使用您在数据库中找到的结果填充它:

while($result = get_results_from_db()) {
    $accountno = $result[accountno];
    $all_records[$accountno] = $result;
}

现在您有一个按帐号索引的数组,因此如果您知道它是帐号,则很容易找到任何记录。因此,您遍历数组以将孩子与父母相关联:

$top_level_records = array();
foreach($all_records AS $record) {
    $parentaccountno = $record[parentaccountno];
    if(!empty($parentaccountno)) {
        $parent = &$all_records[$record[parentaccountno]];
        if(empty($parent['accounts']))
            $parent['accounts'] = array() 
        $parent['accounts'][] = $record;
    }
    else {
        $top_level_records[] = $record;
    }
}
于 2012-06-17T11:48:27.287 回答
0

你所有的结果都是这样的吗?那么,父帐户在哪里?还是我错过了什么?我会简单地重写查询以获得更“线性”的结果,例如:

parentaccountno | accountno | accountname | bla
-----------------------------------------------
000213123       | 123124234 | Hansel      | abc

When every result row looks like this, you can simple create your final array like that:

foreach ($decode as $row) {
    $my_array = [ $row["parentaccountno"] ][ $row["accountno"] ]["accountname"] = $row["accountname"];      
    $my_array = [ $row["parentaccountno"] ][ $row["accountno"] ]["bla"] = $row["bla"];     
}
于 2012-06-17T11:52:24.597 回答
0

I appreciate the answers, but I think the problem is my database query which should contain records of all the parents of an account and not just the parent, using something like SYS_CONNECT_BY_PATH in Oracle SQL.

于 2012-06-17T15:52:29.870 回答