1

ZendFrameworkアプリケーションでこのプログラミングの課題を達成する方法を理解しようとして問題が発生しています。

次のような配列を作成する必要があります。

$array = array(
    0 => stdClass()->monthName
                   ->monthResources = array()
    1 => stdClass()->monthName
                   ->monthResources = array()
);

これは私が使用しなければならない元の配列です:

$resources = array(
    0 => Resource_Model()->date (instance of Zend_Date)
    1 => Resource_Model()->date
    2 => Resource_Model()->date
    //etc...
);

元の配列($resources)はすでに日付(降順)で並べ替えられているため、リソースが月でグループ化された配列を作成する必要があります。stdClassリソースのある月のみが必要なので、リソースが1か月スキップする場合、最終的な配列にその月のオブジェクトは存在しないはずです。

また、これを迅速に処理したいので、コードを最適化する(そしてまだ読みやすい)ことについてのアドバイスは素晴らしいでしょう。どうすればこれを達成できますか?

4

2 に答える 2

1

私の供物。その速度の保証はありませんが、それはO(n)であり、理論的にはあなたの方法よりも速いはずです。これは、一部またはすべての場合に当てはまるとは限りません。ただし、最適化されたものが必要な場合は、プロファイラーを使用して、実行時間の.001%しか占めていないコードのセクションを高速化しようとするのではなく、速度の問題を引き起こしている関数であることを確認する必要があります。(この場合、関数を最適化することによる最大ゲインは.001%になります)

$resources = $this->fetchAll();
$sortedresources = array();
foreach ($resources as $resource) {

    $monthName = $resource->getDate()->get(Zend_Date::MONTH_NAME);

    if ( !isset($sortedresources[$monthName]) ){
        //setup new data for this month name
        $month = new stdClass();
        $month->name = $monthName;
        $month->monthResources = array();
        $sortedresources[$monthName] = $month;
    }

    $sortedresources[$monthName]->monthResources[] = $resource;
}
//return the values of the array, disregarding the keys
//so turn array('feb' => 'obj') to array(0 => 'obj)
return array_values($sortedresources);
于 2009-12-21T01:05:19.827 に答える
0

多分これは役立ちます(擬似コード)

$finalArray = new array();
$tempStdClass = null;

foreach ($resObj in $resources)
{
    if ($tempStdClass == null)
        $tempStdClass = new StdClass($resObj->date);

    if (tempStdClass->monthName != $resObj->date)
    {
        array_push($finalArray, $tempStdClass);
        $tempStdClass = new StdClass($resObj->date);
    }

    array_push($tempStdClass->monthResources, $resObj);    
}
于 2009-12-20T23:21:27.550 に答える