合并2个不同长度的数组 [英] Combine 2 arrays of different length

查看:117
本文介绍了合并2个不同长度的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含100个值的数组(array1).我有另一个具有8个值的数组(array2).我想从array2中获取值并将它们用作键,并在array1中提取这些键的值.

I have an array with 100 values(array1). I have another array with 8 values(array2). I want to take the values from array2 and use them as keys and extract the values in array1 for those keys.

array_combine函数的长度不同,因此无法使用.

The array_combine function won't work as they are of different lengths.

我尝试过

function array_combine2($arr1, $arr2) {
    $count = min(count($arr1), count($arr2));
    return array_combine(array_slice($arr1, 0, $count), array_slice($arr2, 0, $count));
}

但是这不起作用.....这给了我一个带有正确键的数组,但是值不正确,我认为是因为它对array1进行了切片.

But this doesn't work.....this gives me an array with the correct keys, but the values are incorrect, I think because it is slicing array1.

有人可以帮忙吗?我知道,关于这一点已经有很多文献了,但是它们都提供了与上述解决方案非常相似的解决方案.

Could someone give some assistance. There is a fair amount of literature on this already, I know, but they all give solutions very similar to the one above which isn't working.

非常感谢您抽出宝贵的时间.

Many thanks for the time you have taken.

推荐答案

尝试一下.循环第二个数组,并使用array2的值作为array1的索引从array1提取值

Try this. loop the 2nd array and extract the value from array1 with using value of array2 as index for array1

foreach ( $array2 as $arr2 ){
   $temp[]= $array[ $arr2 ];
}
return $temp;

这篇关于合并2个不同长度的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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