PHP循环,日期排序挑战
我在试图找出如何在我的Zend Framework应用程序中实现此编程挑战时遇到困难: 我需要创建一个如下所示的数组:PHP循环,日期排序挑战,php,zend-framework,zend-date,Php,Zend Framework,Zend Date,我在试图找出如何在我的Zend Framework应用程序中实现此编程挑战时遇到困难: 我需要创建一个如下所示的数组: $array = array( 0 => stdClass()->monthName ->monthResources = array() 1 => stdClass()->monthName ->monthResources = array() );
$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
对象
我还希望这个过程能够快速进行,因此任何关于优化代码(并且仍然可读)的建议都会很好。如何实现这一点?也许这有帮助(伪代码)
也许这有帮助(伪代码)
我的提议。不保证它的速度,但它是O(n),理论上应该比你的方法快。这可能并非在任何或所有情况下都是正确的。但是,如果您想要优化某些内容,您应该使用探查器来确保这是导致速度问题的函数,而不是在代码部分只占执行时间的.001%时尝试使代码部分变快。(在这种情况下,优化功能的最大增益为.001%)
我的提议。不保证它的速度,但它是O(n),理论上应该比你的方法快。这可能并非在任何或所有情况下都是正确的。但是,如果您想要优化某些内容,您应该使用探查器来确保这是导致速度问题的函数,而不是在代码部分只占执行时间的.001%时尝试使代码部分变快。(在这种情况下,优化功能的最大增益为.001%)
查看
Resource\u Object()
的代码会有帮助,否则答案会过于泛化。查看Resource\u Object()
的代码会有帮助,否则答案会过于泛化。我只提到我希望对其进行优化,因为我能想到的唯一方法是对数组进行多次迭代(我知道可能没有必要)。我只提到我希望对它进行优化,因为我能想到的唯一方法是多次遍历数组(我知道可能没有必要)。
$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);
}
$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);