合并后的数组中的PHP不同的方式 [英] Merge array in a different way in PHP

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

问题描述

我有这两个数组:

$array1 = array( '0' => 'apple', '1' => ''   , '2' => 'cucumber' );

$array2 = array( '0' => '',      '1' => 'bmw', '2' => 'chrysler' );

如果我这样做是为了合并这些阵列:

if I do this to merge these arrays:

$result_arr = array_merge($array1, $array2);
print_r( count ( array_filter($result_arr) ) );

输出将是4。

不过,我需要数3。因此,当在同一位置(相同的密钥)计数它只有一次两件事情。

However, I need to get the number 3. So, when there are two things on the same position (same key) count it only once.

是否有可能合并/计数数组中的元素这样?

Is it possible to merge/count elements in arrays like that?

推荐答案

一个可能的方法来生成这些阵列的联盟:

One possible way to generate a 'union' of those arrays:

$first  = array( '0' => 'apple', '1' => ''   , '2' => 'cucumber', 3 => '');
$second = array( '0' => '',      '1' => 'bmw', '2' => 'chrysler', 3 => '');

$result = array_map(function($a, $b) {
  return $a ?: $b;
}, $first, $second);
print_r($result); 
/* 
[0] => 'apple'
[1] => 'bmw'
[2] => 'cucumber'
[3] => ''
*/

演示

将所得的阵列将要么与来自第一阵列非空元素或(如果检查用于非空失败)与被填充的任何的从第二数组元素的类型 - 后者将成为作为一种后备的。

The resulting array will be filled either with non-empty elements from the first array or (if check for non-emptiness fails) with any type of elements from the second array - the latter will serve as a kind of fallback.

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

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