合并在PHP两个数组(键和内容) [英] Merge two arrays (key and content) in PHP

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

问题描述

我有这样一个数组以下

阵列([0] =>TXT1[1] =>TXT2[2] =>txt3)

Array ( [0] => "txt1" [1] => "txt2" [2] => "txt3")

我有另一个数组一样,但不同的内容:
阵列([0] =>在[2] = ON>)

I have another array like it but with different content : Array ( [0] => on [2] => on)

的目的是获得与第二和第一内容的密钥的最后阵列,它就像将它们合并。

The aim is to get a final array with the keys of the second and the content of the first, it's like merging them.

所以,最后的结果是:阵列([0] =>TXT1[2] =>txt3),这将是更好的键更改为0 - 1,但一个简单的问题,让我们的工作重点在合并他们一对一的。

So that the final result is : Array ( [0] => "txt1" [2] => "txt3") It would be better to change the keys to 0 - 1, but that a trivial issue, let's focus on merging them one to one.

推荐答案

要做到这一点是 array_intersect_key 查看PHP文档)。它从第一阵列抓住顺利通过对应于传递的所有其他数组键present的值。

The easiest way to do this is with array_intersect_key (See the PHP Docs). It grabs the values from the first array passed corresponding to the keys present in all other arrays passed.

所以,你的例子是这样的:

So, your example would look like this:

$a = array(0 => "txt1", 1 => "txt2", 2 => "txt3");
$b = array(0 => 1, 2 => 1);
$c = array_intersect_key($a, $b);
print_r($c);

打印:

Array
(
    [0] => txt1
    [2] => txt3
)

这篇关于合并在PHP两个数组(键和内容)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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