gpt4 book ai didi

php - 使用 array_multisort 对数组进行排序

转载 作者:可可西里 更新时间:2023-11-01 12:58:05 25 4
gpt4 key购买 nike

我有以下数组:

$array = array(
'note' => array(),
'year' => array('2011','2010', '2012'),
'type' => array('conference', 'journal', 'conference'),
);

然后我使用以下函数使用字段类型和另一个数组对数组进行排序:

function array_multisort_by_order(array $array, $by, array $order)
{
$order = array_flip($order);
$params[] = $array[$by];
foreach($params[0] as &$v) $v = $order[$v];
foreach($array as &$v) $params[] = &$v; unset($v);
call_user_func_array('array_multisort', $params);
return $array;
}

当我调用以下函数时,出现以下错误:

$array = array_multisort_by_order($array, 'type', array('conference', 'journal'));

print_r($array['type']);

错误:

Warning: array_multisort(): Array sizes are inconsistent.

我知道数组是不一致的。有更好的功能可以使用吗?

请检查:codepad

期望的输出:

Array
(
[note] => Array
(
[0] =>
[1] =>
[2] =>
)

[year] => Array
(
[0] => 2011
[1] => 2012
[2] => 2010
)

[type] => Array
(
[0] => conference
[1] => conference
[2] => journal
)

)

示例 2:

数组

 $array = array(
'note' => array([0]=>'test1', [1]=>'test2'),
'year' => array([0]=>'2011', [2]=>'2012'),
'type' => array([0]=>'conference',[1]=>'journal', [2]=>'conference'),
);

期望的结果 2

Array
(
[note] => Array
(
[0] => test1
[1] =>
[2] => tes2
)

[year] => Array
(
[0] => 2011
[1] => 2012
[2] =>
)

[type] => Array
(
[0] => conference
[1] => conference
[2] => journal
)

)

谢谢

最佳答案

好的,那么,首先想到的解决方案之一是添加空值以使其保持一致:

function array_multisort_by_order(array $array, $by, array $order)
{
$max = max(array_map('count',$array));
//or, alternatively, depending on input (if there are no 'complete' subarrays):
//$max = max(array_map(function($arr){return max(array_keys($arr));},$array))+1;

//ADDITION: negative numeric keys:
$min = min(array_map(function($arr){return min(array_keys($arr));},$array));
$width = $max - min(0,$min);

foreach($array as &$sub){
// $addin = array_diff_key(array_fill(0,$max,null),$sub);
// $addin changed for negative keys:
$addin = array_diff_key(array_combine(range($min,$max),array_fill(0,$width,null)),$sub);
$sub = $addin + $sub;
ksort($sub);
}
$order = array_flip($order);
$params[] = $array[$by];
foreach($params[0] as &$v) $v = $order[$v];
foreach($array as &$v) $params[] = &$v; unset($v);
call_user_func_array('array_multisort', $params);
//no closeures here:
//foreach($array as &$sub) $sub = array_filter(function($a){return !is_null($a);},$sub);
$filter = create_function('$a','return !is_null($a);');
foreach($array as &$sub) $sub = array_filter($sub,$filter);
return $array;
}

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

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