我在查找Zend Framework应用程序中如何实现此编程挑战时遇到了麻烦:
我需要创建一个如下所示的数组:
$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
个对象。
我也希望这可以快速处理,因此任何有关优化代码(并且仍然可读)的建议都会很棒。我怎样才能做到这一点?
答案 0 :(得分: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);
答案 1 :(得分: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);
}