【问题标题】:Efficient way of searching an index with 2 criterias on a multidimensional array in php在php中的多维数组上搜索具有2个条件的索引的有效方法
【发布时间】:2020-05-01 18:48:01
【问题描述】:

我需要找到给定两个值的多维数组的索引,其中一个值重复多次,因为它是州和城市的列表,这是一个示例

array(
        99773000 => array('State' => 'ANTIOQUIA', 'City' => 'CUMARIBO'),
        99624000 => array('State' => 'ANTIOQUIA', 'City' => 'SANTA ROSALIA'),
        99524000 => array('State' => 'VICHADA', 'City' => 'LA PRIMAVERA'),
        99001000 => array('State' => 'VICHADA', 'City' => 'PUERTO CARREÑO'),
        .....
        xxxxxxxx => array('State') => etc......
);

现在,我在函数中收到一个州和一个城市,我需要返回索引,这就是我现在的做法:

        foreach ( $array as $index => $state_and_city ) {

            $current_state = $state_and_city['State'];

            $current_city = $state_and_city['City'];

            if( $current_state == $state  && $current_city == $city) {
                return $index;
            }
        }

        return '';

我想知道是否有更有效的方法来做到这一点?

【问题讨论】:

    标签: php arrays multidimensional-array


    【解决方案1】:

    这里你只需要从内部数组中获取键,这可以通过array_search函数来实现。

     foreach ($array as $index => $state_and_city ) {
    
                $current_state = $state_and_city['State'];
    
                $current_city = $state_and_city['City'];
    
               $state_key = array_search($current_state,$index);
               $city_key = array_search($current_city,$index);
    
    
                if($state_key == $state  && $city_key == $city) {
                    return $index;
                }
            }
    
            return '';
    

    【讨论】:

    • 好吧,我想知道为什么它比其他方法更快...我的意思是技术原因。
    • 因为在最初提到的方法中,一个添加的循环会导致它自己执行的时间差。
    • 现在它全部在一个循环中,所以它可以让事情快速执行。
    • 是的,但它基本上和我已经做过的一样,不同之处在于你正在使用这个 array_search 额外方法,我认为这增加了我已经拥有的额外步骤......所以这就是为什么我问。
    • 不,您只会得到所需键的值,但通过使用我的代码,您将从所需的数组中获取键,并可以将它们用于比较我们这两个代码的进一步操作时间的作用如此之大,但它都是关于正确性的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2014-12-03
    • 2014-04-11
    • 2016-05-29
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    相关资源
    最近更新 更多