我有1D arrayA和2D arrayB。
arrayA[0] = 'D'
arrayA[1] = 'U'
arrayA[3] = 'R'
arrayA[4] = 'B'
arrayA[5] = 'S'
arrayA[6] = 'H'
arrayB[0][0] = 'D' arrayB[0][1] = 2
arrayB[1][0] = 'B' arrayB[1][1] = 1
arrayB[2][0] = 'R' arrayB[2][1] = 1
arrayB[3][0] = 'U' arrayB[3][1] = 1
arrayB[4][0] = 'H' arrayB[4][1] = 0
arrayB[5][0] = 'S' arrayB[5][1] = 0
arrayB [x] [y]按照y。
进行排序我必须使用字母创建一个新数组,首先优先于arrayB [x] [y]中的y。 但是在y中有一些相同的值,1三次和0两次。 在这种情况下,类似的值将根据arrayA进行排序。
,新数组的排序方式如下:
D, U, R, B, S, H
我怎样才能有效地做到这一点?
提前致谢
答案 0 :(得分:0)
我试过这个并且工作正常。 a1是1d数组,a2是2d。
编辑:现在可以使用了。
function sortArr($a1, $a2) {
$t1 = array();
foreach ($a1 as $v) {
$t2 = array();
foreach ($a2 as $i=>$k) {
if ($k[0] == $v) {
$t2[0] = $k[0];
$t2[1] = $k[1];
$t1[$i] = $t2;
break;
}
}
}
return $t1;
}
答案 1 :(得分:0)
在下面的代码中,$string
对应arrayB[x][0]
,$weight
对应arrayB[x][1]
,$order
对应arrayA
:
<?php
$string = str_split('DBRUHS');
$weight = str_split('211100');
$result = '';
function my_sort($a, $b)
{
$order = str_split('DURBSH');
$a = array_search($a, $order);
$b = array_search($b, $order);
if ($a === $b) return 0;
if ($a === FALSE) return -1;
if ($b === FALSE) return 1;
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
}
arsort($weight);
$current_priority = -1;
$substring = array();
$max = count($weight);
$count = 1;
foreach ($weight as $position => $priority)
{
if ($count++ == $max)
{
$substring[] .= $string[$position];
$priority = $current_priority + 1;
}
if ($current_priority != $priority)
{
if (!empty($substring))
{
usort($substring, 'my_sort');
$result .= implode('', $substring);
}
$current_priority = $priority;
$substring = array($string[$position]);
}
else
{
$substring[] = $string[$position];
}
}
print_r(str_split($result));
?>