【问题标题】:Is that possible to know if element exists inside an array without looping through the array?是否可以在不遍历数组的情况下知道元素是否存在于数组中?
【发布时间】:2021-07-02 02:15:15
【问题描述】:

我有一个结构相同的元素数组。 这是一个例子:

<?php
    $arr =
        [
            [
                "el_name" => "abcd",
                "el_data" => "raw_dataè_15264df156g18df",
            ],
            [
                "el_name" => "efgh",
                "el_data" => "raw_data_sd25g",
            ],
            [
                "el_name" => "ijkl",
                "el_data" => "raw_data_dfdfgn48",
            ],
            [
                "el_name" => "mnop",
                "el_data" => "raw_data_²545",
            ],
        ];
    
    $new_el = [
        "el_name" => "efgh",
        "el_data" => "raw_data_sd25g",
    ];

我想添加$new_el,前提是它尚未出现在$arr 中。如果php有array_element_exists()函数会很方便;-)

为了这个问题,我尝试了这个:

$exists = false;
foreach($arr as $el) {
    $equal=true;
    foreach(array_keys($el) as $key) {
        if(isset($new_el[$key]) && $new_el[$key] === $el[$key]) {
            null;
            //equality
        } else {
            $equal = false;
        }
    }
    if($equal === true) {
        $exists = true;
        break;
    }
}
if($exists === true ) {
    echo '$new_el already exists in $arr' . PHP_EOL;
} else {
    echo '$new_el doesn\'t still exists in $arr' . PHP_EOL;
    $arr[] = $new_el;
}

您认为还有更高效、“更简单”的方法吗?...

【问题讨论】:

    标签: php arrays algorithm


    【解决方案1】:

    您可能正在寻找in_array() 函数。

    in_array($new_el, $arr);
    

    返回true

    【讨论】:

    • 我的错!它有效,这是我一直在寻找的内置功能
    • 这个完美。删除了我的。 +1
    【解决方案2】:
    
    function array_element_exists($new_el,$arr){
        $found = array_filter($arr, function($arr) use ($new_el) {
            return $arr['el_name'] === $new_el['el_name'] && 
                $arr['el_data'] === $new_el['el_data'];
        });
        return $found;
    }
    
      
    $exsist = ["el_name" => "efgh","el_data" => "raw_data_sd25g"];
    $notExsist = ["el_name" => "newName","el_data" => "newData",];
    
    //will not be added since it is already exist
    if (!array_element_exists($exsist,$arr)) {
        $arr[] = $exsist;
    }
    
    //will be added because it is new and not exist in `$arr`
    if (!array_element_exists($notExsist,$arr)) {
        $arr[] = $notExsist;
    }
    

    【讨论】:

    • 看起来很完美...!
    猜你喜欢
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 2021-09-20
    • 2019-05-01
    • 2016-06-26
    相关资源
    最近更新 更多