0

ねえ、私はこれを約3日間解決しようとしてきましたが、役に立ちませんでした。

次のような 2 次元配列があります。

$testObject = array(
    array(
        "id"=> 1,
        "parentID"=> 0,
        "insuCount"=> 300,
        "totalInsuCount"=> '',
        "childrenCount" => ''
    ),
    array(
        "id"=> 21,
        "parentID"=> 1,
        "insuCount"=> 136,
        "totalInsuCount"=> '',
        "childrenCount" => ''
    ),
    array(
        "id"=> 52,
        "parentID"=> 21,
        "insuCount"=> 99,
        "totalInsuCount"=> '',
        "childrenCount" => ''
    )
);

配列には子/親があり、insuCount、totalInsuCount、childrenCount もあります。階層の最下部から最上位の親までの issuCount を合計し、その結果を totalInsuCount に設定しようとしています。

また、私の状況の一番上の親には2人の子供がいるように、ネストされた子供もカウントされます。

したがって、基本的に私の正しい配列は次のようになります。

$testObject = array(
    array(
        "id"=> 1,
        "parentID"=> 0,
        "insuCount"=> 300,
        "totalInsuCount"=> 535,
        "childrenCount" => 2
    ),
    array(
        "id"=> 21,
        "parentID"=> 1,
        "insuCount"=> 136,
        "totalInsuCount"=> 235,
        "childrenCount" => 1
    ),
    array(
        "id"=> 52,
        "parentID"=> 21,
        "insuCount"=> 99,
        "totalInsuCount"=> 300,
        "childrenCount" => 0
    )
);

誰もがどうやってそれを行うのか手がかりを持っています.3日間ほどそれに取り組んできましたが、今では方法がわかりません.

ありがとうございます。

4

3 に答える 3

1

最初に、ID と等しいキーを持つ配列に配列を変換する必要があります。ID で任意の要素に直接アクセスできます。

$testObject = array(
     1 => array(
        "id"=> 1,
        "parentID"=> 0,
        "insuCount"=> 300,
        "totalInsuCount"=> '',
        "childrenCount" => ''
     ),
     21 => array(
        "id"=> 21,
        "parentID"=> 1,
        "insuCount"=> 136,
        "totalInsuCount"=> '',
        "childrenCount" => ''
     ),
     52 => array(
        "id"=> 52,
        "parentID"=> 21,
        "insuCount"=> 99,
        "totalInsuCount"=> '',
        "childrenCount" => ''
     )
);

これを実装するのは明らかです。だから私はあなたに解決策を残します。

これで、すべての親の数を簡単に計算できます。

foreach ($testObject as $id => &$data){

    $parentId = $data['parentID'];
    while ($parentId && isset($testObject[$parentId])){
        $parentData = &$testObject[$parentId];

        $parentData["childrenCount"]++;
        $parentData["totalInsuCount"] += $data["insuCount"];

        $parentId = $parentData['parentID'];
    }

    $data["totalInsuCount"] += $data["insuCount"];
}

print_r($testObject);

アップデート

すべての子がカウントされ、ルート エントリに属していることをテストします。

$totalChildren = 0;
foreach ($testObject as $data){
    //sum all childrens of root elements
    if (!$data['parentID']) $totalChildren += $data["childrenCount"] + 1;
}   

echo 'Children counted: ' .$totalChildren;
echo "<br>";
echo 'Total elements: ' .sizeof($testObject);

また、一部のエントリが自己参照されるため、初期配列を準備する必要がありました。

$newTestObject = array();
foreach ($testObject as $data){
    if ($data['id'] == $data['parentID']) $data['parentID'] = 0;
    $newTestObject[$data['id']] = $data;
}

$testObject = $newTestObject;
于 2013-06-04T17:16:25.910 に答える