添加到数组(如果还不存在) [英] add to array if it isn't there already

查看:101
本文介绍了添加到数组(如果还不存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当元素不在数组中时才如何将其添加到数组中?我有以下内容:

How do I add elements to an array only if they aren't in there already? I have the following:

$a=array();
// organize the array
foreach($array as $k=>$v){
    foreach($v as $key=>$value){
        if($key=='key'){
        $a[]=$value;
        }
    }
}

print_r($a);

//输出

Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 1
[4] => 2
[5] => 3
[6] => 4
[7] => 5
[8] => 6

)

相反,我希望$ a包含唯一值. (我知道我可以使用array_unique获得所需的结果,但我只是想知道)

Instead, I want $a to consist of the unique values. (I know I can use array_unique to get the desired results but I just want to know)

推荐答案

您必须对照 in_array检查每个值:

$a=array();
// organize the array by cusip
foreach($array as $k=>$v){
    foreach($v as $key=>$value){
        if(!in_array($value, $a)){
        $a[]=$value;
        }
    }
}

这篇关于添加到数组(如果还不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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