保留一个元素的顺序但在 php 数组中打乱另一个元素?
考虑一个 m 维 php 数组,如下所示:
print_r($arr)
Array (
[0] => Array ( [stimid] => 6 [list] => L01 )
[1] => Array ( [stimid] => 3 [list] => L01 )
[2] => Array ( [stimid] => 2 [list] => L02 )
[3] => Array ( [stimid] => 5 [list] => L02 )
[4] => Array ( [stimid] => 1 [list] => L03 )
[5] => Array ( [stimid] => 4 [list] => L03 )
)
请注意,“stimid”元素是随机顺序的,但“list”元素是升序的。我只是对该数组进行洗牌,以便“列表”元素保持连续。例如,我希望新数组的顺序是:
print_r($new_arr)
Array (
[0] => Array ( [stimid] => 1 [list] => L03 )
[1] => Array ( [stimid] => 4 [list] => L03 )
[2] => Array ( [stimid] => 3 [list] => L01 )
[3] => Array ( [stimid] => 6 [list] => L01 )
[4] => Array ( [stimid] => 2 [list] => L02 )
[5] => Array ( [stimid] => 5 [list] => L02 )
)
另请注意,每个“列表”类型中的行的顺序不需要保留其顺序。
这可能是一个非常简单的问题,但我似乎无法解决它! 任何帮助表示赞赏。
Consider a m-dimensional php array that looks like this:
print_r($arr)
Array (
[0] => Array ( [stimid] => 6 [list] => L01 )
[1] => Array ( [stimid] => 3 [list] => L01 )
[2] => Array ( [stimid] => 2 [list] => L02 )
[3] => Array ( [stimid] => 5 [list] => L02 )
[4] => Array ( [stimid] => 1 [list] => L03 )
[5] => Array ( [stimid] => 4 [list] => L03 )
)
Notice that the 'stimid' element is in random order but the 'list' element is ascending. I'm simply after a shuffle of this array such that the 'list' elements remain contiguous. What I'd like the order of the new array to be, for example, is:
print_r($new_arr)
Array (
[0] => Array ( [stimid] => 1 [list] => L03 )
[1] => Array ( [stimid] => 4 [list] => L03 )
[2] => Array ( [stimid] => 3 [list] => L01 )
[3] => Array ( [stimid] => 6 [list] => L01 )
[4] => Array ( [stimid] => 2 [list] => L02 )
[5] => Array ( [stimid] => 5 [list] => L02 )
)
Also notice that the order of the rows within each 'list' type need not retain their order.
This may be a very simple problem, but I can't seem to solve it!
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不漂亮或高效,但是:
输出:
Not pretty or efficient but:
Output:
您可以这样做:
适用于 1 层深度的嵌套数组。
You can do it like this:
Works for nested array's on 1 level deep.