合并并排两个阵列侧,其中一个可以比另一个更短的 [英] Merge two arrays side by side where one can be shorter than the other

查看:151
本文介绍了合并并排两个阵列侧,其中一个可以比另一个更短的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有热点和新的新闻文章。我想显示他们并排在视图中。当然,这可能是因为有比新的消息(在早晨为例),反之亦然更多热点新闻。这将导致各列的凹凸长度

Say I have hot and new news articles. I want to display them side by side in the view. It may of course be that there are more hot news than new news (at the morning for example) and vice versa. This would lead to an uneven length of the columns.

这就是为什么我要建两个数组。一个与热点新闻,一个新的。

That's why I'm building two arrays. One with the hot news and one with the new ones.

$hot = array(
    'hotObj 1',
    'hotObj 2',
    'hotObj 3',
    'hotObj 4',
);

$new = array(
    'newObj 1',
    'newObj 2',
);

我要的结果是这样的:

What I want as a result is this:

$hot = array(
    'hotObj 1',
    'newObj 1',
    'hotObj 2',
    'newObj 2',
    'hotObj 3',
    'hotObj 4',
);

我怎样才能做到这一点?它不应该的问题该数组是更长的时间。
array_merge()只想把第二排在最后这不是我想要的。

How can I achieve this? It shouldn't matter which array is longer. array_merge() would just put the second array at the end which is not what I want.

推荐答案

可以实现它只需使用循环,而无需使用排序 array_merge 之类的函数为

You can achieve it simply using for loop, without using sort or array_merge function like as

$count = (count($hot) > count($new)) ? count($hot) : count($new);

$result = [];

for($i= 0; $i < $count;$i++){
    if(isset($hot[$i])){
        $result[] = $hot[$i];
    }
    if(isset($new[$i])){
        $result[] = $new[$i];
    }
}
print_r($result);

输出:

Array
(
    [0] => hotObj 1
    [1] => newObj 1
    [2] => hotObj 2
    [3] => newObj 2
    [4] => hotObj 3
    [5] => hotObj 4
)

演示

这篇关于合并并排两个阵列侧,其中一个可以比另一个更短的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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