php数组对数组的键和键的数组的区别? [英] php array difference against keys of an array and an array of keys?

查看:82
本文介绍了php数组对数组的键和键的数组的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有两个数组:

$a=array('1'=>'Apple','2'=>'Microsoft',
         '3'=>'Microapple','4'=>'Applesoft','5'=>'Softapple');
$b=array(1,3);

其中$ b数组表示要区别的数组$ a的键.

Where $b array represents the keys of array $a to be differentiated against.

我们希望收到另一个具有以下值的数组$ c:

And we expect to receive another array $c with the following values:

$c=array('2'=>'Microsoft','4'=>'Applesoft','5'=>'Softapple');

在php手册中,有两个功能:

In php manual there are two functions:

array_diff($array1,$array2);    //difference of values
array_diff_key($array1,$array2);//difference of keys

但以上两种方法都不适用.

But neither of the above is applicable here.

我们该怎么办?

修改

感谢大家的贡献.

我在两个预定义的数组上执行了一些基准测试,如下所示:

I performed some benchmarks on two arrays predefined as follows:

for ($i=0; $i < 10000; $i++) {    //add 10000 values
    $a[]=mt_rand(0, 1000000); //just some random number as a value
}
for ($i=0; $i < 10000; $i++) {    //add 10000 values as keys of a
    $b[]=mt_rand(0, 1000);    
}        //randomly from 0 to 1000 (eg does not cover all the range of keys)

每次测试也进行了10000次, Nanne 的解决方案的平均时间为:

Each test was also taken 10000 times, the average time of Nanne's solution was:

0.013398

decereé之一:

0.014865

这也是极好的.

...与in_array()的其他建议不同,但(该答案已删除):

...Unlike some other suggestion with in_array() but (that answer was deleted):

foreach ($a as $key => $value)
if (!in_array($key, $b)) 
$c[$key] = $value;

以上所述平均完成2秒.出于显而易见的原因,in_array()将不得不遍历$ b来检查值是否存在.上面是一个很好的例子,说明如何做到这一点!:-)

The above did 2 seconds on average. For the obvious reason that in_array() would have to loop through the $b to check whether the value existed. The above is an excellent example how not to do it! :-)

推荐答案

我只是将其编码为:

$c = $a;
foreach ($b as $removeKey) {
    unset($c[$removeKey]);
}

这篇关于php数组对数组的键和键的数组的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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