gpt4 book ai didi

php - 对 2 深数组进行多排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:24:57 24 4
gpt4 key购买 nike

考虑以下多重排序方法。在这种情况下,我有一系列具有特定开始日期的项目。显示示例数组:

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;
}

最佳答案

已更新。这允许您为带分隔符的字段传递一个字符串,它是您所需字段的路径。

$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
)

)

)

关于php - 对 2 深数组进行多排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18749032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com