如何结合随机两个数组在PHP [英] How to Combine two arrays randomly in PHP

查看:196
本文介绍了如何结合随机两个数组在PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何两个数组合并成单一,我以这样的方式,要求这一点,第三组合数组应该包含一个阵列的一个值,并从其他阵列等下一个..或(它可能是随机的)
例如:

  $ ARR1 =(1,2,3,4,5);
$ ARR2 =(10,20,30,40,50);

和联合阵列

  $ ARR3 =(1,10,2,20,3,30,...);


解决方案

我也将产生你在你的问题有精确的输出乐趣做了一个功能。不管两个阵列的大小,将工作

 函数FosMerge($ ARR1,$ ARR2){
    $解析度=阵列();
    $ ARR1 = array_reverse($ ARR1);
    $ ARR2 = array_reverse($ ARR2);
    的foreach($ ARR1为A1 $){
        如果(计数($ ARR1)== 0){
            打破;
        }
        array_push($资源,array_pop($ ARR1));
        如果(计数($ ARR2)!= 0){
            array_push($资源,array_pop($ ARR2));
        }
    }
    返回array_merge($资源,$ ARR2);
}

How to combine two arrays into single one and i am requesting this in such a way that the 3rd combination array should contains one value from one array and the next one from other array and so on.. or ( it could be random) ex:

$arr1 = (1, 2, 3, 4, 5);
$arr2 = (10, 20, 30, 40, 50);

and combined array

$arr3 = (1, 10, 2, 20, 3, 30, ...);

解决方案

I also made a function for fun that will produce the exact output you had in your question. It will work regardless of the size of the two arrays.

function FosMerge($arr1, $arr2) {
    $res=array();
    $arr1=array_reverse($arr1);
    $arr2=array_reverse($arr2);
    foreach ($arr1 as $a1) {
        if (count($arr1)==0) {
            break;
        }
        array_push($res, array_pop($arr1));
        if (count($arr2)!=0) {
            array_push($res, array_pop($arr2));
        }
    }
    return array_merge($res, $arr2);
}

这篇关于如何结合随机两个数组在PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆