通过中间键启动重新排序PHP数组(圆形分类) [英] Re-order PHP array by middle key as start (Circular Sorting)
问题描述
很基本的问题,但是我也遇到了一些麻烦上PHP.NET寻找答案。
very basic question however I have had some trouble finding the answers on PHP.NET.
我有以下数组:
Array (
[1] => Array
(
[1] => 4
[2] => 1
[3] => 5
[4] => 3
)
[2] => Array
(
[5] => 2
[6] => 8
[7] => 7
[8] => 6
)
[3] => Array
(
[9] => 10
[10] => 9
[11] => 12
[12] => 11
)
[4] => Array
(
[13] => 15
[14] => 16
[15] => 14
[16] => 13
)
)
欲被重新排序阵列,使得在第一个系列阵列的键号3成为第一,那么剩下的是从那里重新排序,以最终得到的结果是:
I want the array to be re-ordered so that the key number 3 in the first series of the array becomes the first, then the rest to be re-ordered from there to eventually get the result of:
Array (
[3] => Array
(
[9] => 10
[10] => 9
[11] => 12
[12] => 11
)
[4] => Array
(
[13] => 15
[14] => 16
[15] => 14
[16] => 13
)
[1] => Array
(
[1] => 4
[2] => 1
[3] => 5
[4] => 3
)
[2] => Array
(
[5] => 2
[6] => 8
[7] => 7
[8] => 6
)
)
我要寻找一种方式来做到这一点,所以我可以定义数组,然后第一级关键,我需要进行排序,然后它会以这种方式返回数组。
I am looking for a way to do this so I can define the array, then the first level key I need to sort by, and then it will return the array in this way.
标准的PHP按键似乎并没有提供这样的事情,所以这将是很好的能够有一个单独的函数,比如$ newArray = reorder_array($数组$关键);
The standard PHP keys didn't seem to offer something like this, so it would be good to be able to have a separate function such as $newArray = reorder_array($array, $key);
我不要求第二级的任何排序,只有最初的4个主要/第一级阵列部分
I don't require any sorting of the second level, only the initial 4 main / first level array sections.
您帮助是极大的pciated因为我一直坐在这个一段时间没有一个明确的和简单的解决方案AP $ P $。
You help is greatly appreciated as I have been sitting on this one for awhile without a clear and simple solution.
推荐答案
您重新排序可以用一个的foreach
循环简单地实现,如:
You re-ordering can be simply implemented with one foreach
loop, like:
function reorderArray($array, $key)
{
$found = false;
foreach($array as $k=>$v)
{
$found = $found || $k===$key;
if(!$found)
{
unset($array[$k]);
$array[$k] = $v;
}
//else break can be added for performance issues
}
return $array;
}
与使用
$array=[1=>'foo', 4=>'bar', 9=>'baz', 'test'=>51];
var_dump(reorderArray($array, 9));
var_dump(reorderArray($array, 'test'));
var_dump(reorderArray($array, 'no_such_key'));//original array in result
这个演示。如果按键是连续的数字,但是,这可以很容易地与 实施array_slice()
通话。
-check this demo. If keys are consecutive numerics, however, this can be easily implemented with array_slice()
calls.
这篇关于通过中间键启动重新排序PHP数组(圆形分类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!