考虑下面的多排序方法。在本例中,我有一个具有特定开始日期的项目数组。示例数组显示:
0 -> array('title' => 'hello',
'attributes' => array('id' => 4, 'startdate' => '2013-06-11')),
1 -> array('title' => 'hello second entry',
'attributes' => array('id' => 6, 'startdate' => '2013-04-11'))你可以看到第二项应该在第一项之前。当前使用我的调用将无法工作,因为它只检查数组的深度1。
$albums = $this->multiSort($items, "SORT_ASC", 'startdate', true);如何将此方法修改为对数组中的项进行深度搜索的最佳方法。更好的办法是能够指定深度键。我希望避免在方法中添加额外的参数。
我可以像这样调用这个方法,然后编写一个for循环来获取关键数据,但是嵌套for循环并不是我想要做的事情。
$albums = $this->multiSort($items, "SORT_ASC", array('attributes', 'startdate') , true);对于我的情况,优化这个方法的最佳方法是什么?
public function multiSort($data, $sortDirection, $field, $isDate) {
if(empty($data) || !is_array($data) || count($data) < 2) {
return $data;
}
foreach ($data as $key => $row) {
$orderByDate[$key] = ($isDate ? strtotime($row[$field]) : $row[$field]);
}
if($sortDirection == "SORT_DESC") {
array_multisort($orderByDate, SORT_DESC, $data);
} else {
array_multisort($orderByDate, SORT_ASC, $data);
}
return $data;
}发布于 2013-09-11 19:39:33
最新情况。这允许您传入一个字符串,用于字段,该字段是分隔的,并且是指向所需字段的路径。
$items = Array();
$items[0] = array('title' => 'hello',
'attributes' => array('id' => 4, 'startdate' => '2013-06-11'));
$items[1] = array('title' => 'hello second entry',
'attributes' => array('id' => 6, 'startdate' => '2013-04-11'));
function multiSort($data, $sortDirection, $field, $isDate) {
if(empty($data) || !is_array($data) || count($data) < 2) {
return $data;
}
// Parse our search field path
$parts = explode("/", $field);
foreach ($data as $key => $row) {
$temp = &$row;
foreach($parts as $key2) {
$temp = &$temp[$key2];
}
//$orderByDate[$key] = ($isDate ? strtotime($row['attributes'][$field]) : $row['attributes'][$field]);
$orderByDate[$key] = ($isDate ? strtotime($temp) : $temp);
}
unset($temp);
if($sortDirection == "SORT_DESC") {
array_multisort($orderByDate, SORT_DESC, $data);
} else {
array_multisort($orderByDate, SORT_ASC, $data);
}
return $data;
}
$albums = multiSort($items, "SORT_ASC", 'attributes/startdate', true);
print_r($albums);输出:
Array
(
[0] => Array
(
[title] => hello second entry
[attributes] => Array
(
[id] => 6
[startdate] => 2013-04-11
)
)
[1] => Array
(
[title] => hello
[attributes] => Array
(
[id] => 4
[startdate] => 2013-06-11
)
)
)https://stackoverflow.com/questions/18749032
复制相似问题