如何在PHP中对数组进行混洗以使所有行互换?

时间:2017-03-24 05:58:39

标签: php arrays

我有一个数组,它根据视频喜欢按降序排列视频数据。这是我的数组: -

Array $video_order_list
(
    [0] => Array
        (
            [video_id] => 1
            [video_title] => A1
            [video_like] => 120
        )

    [1] => Array
        (
            [video_id] => 3
            [video_title] => A3
            [video_like] => 73
        )   

    [2] => Array
        (
            [video_id] => 2
            [video_title] => A2
            [video_like] => 63
        )

    [3] => Array
        (
            [video_id] => 4
            [video_title] => A4
            [video_like] => 55
        )

    [4] => Array
        (
            [video_id] => 5
            [video_title] => A5
            [video_like] => 40
        )       

    [5] => Array
        (
            [video_id] => 6
            [video_title] => A6
            [video_like] => 10
        )   

    [6] => Array
        (
            [video_id] => 7
            [video_title] => A7
            [video_like] => 3
        )
)

我将数组复制到另一个数组中: -

$random_list = $video_order_list;

然后我想改组数组,为此我使用了它: -

shuffle($random_list);

但是,我的洗牌阵列有可能是这样的: -

Array $random_list
(
    [0] => Array
        (
            [video_id] => 2
            [video_title] => A2
            [video_like] => 63
        )

    [1] => Array
        (
            [video_id] => 3
            [video_title] => A3
            [video_like] => 73
        )   

    [2] => Array
        (
            [video_id] => 7
            [video_title] => A7
            [video_like] => 3
        )

    [3] => Array
        (
            [video_id] => 4
            [video_title] => A4
            [video_like] => 55
        )

    [4] => Array
        (
            [video_id] => 6
            [video_title] => A6
            [video_like] => 10
        )

    [5] => Array
        (
            [video_id] => 5
            [video_title] => A5
            [video_like] => 40
        )       

    [6] => Array
        (
            [video_id] => 1
            [video_title] => A1
            [video_like] => 120
        )   
)

看到video_id = 4仍然在第3个索引(第4个位置)。我该如何检查这个问题?

1 个答案:

答案 0 :(得分:1)

您可以创建一个函数checkArr()来检查数组中的任何元素是否在同一个地方,如果不匹配则返回false,并在while循环中使用shuffle()将条件保持为checkArr()