【问题标题】:Recursive array_search递归数组搜索
【发布时间】:2015-04-12 21:53:01
【问题描述】:

我有一个多维数组:

$categories = array(
    array(
        'CategoryID' => 14308,
        'CategoryLevel' => 1,
        'CategoryName' => 'Alcohol & Food',
        'CategoryParentID' => 14308
    ),
    // CHILD CATEGORIES
    array(
        array(
            'CategoryID' => 179836,
            'CategoryLevel' => 2,
            'CategoryName' => 'Alcohol & Alcohol Mixes',
            'CategoryParentID' => 14308
        ),
        array(
            array(
                'CategoryID' => 172528,
                'CategoryLevel' => 2,
                'CategoryName' => 'Antipasto, Savoury',
                'CategoryParentID' => 14308
            )
        )
    )
);

我需要获取索引的确切位置,并且由于array_search 不适用于多维数组,我正在使用 PHP 手册页上提供的函数之一。

function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return $current_key;
        }
    }
    return false;
}

.. 但它也只返回第一个数组的键:

echo recursive_array_search(172528, $categories); // outputs 1

我期待:

[1][1][0]

【问题讨论】:

    标签: php arrays search


    【解决方案1】:

    你可以像这样改变你的递归函数,这应该会给你解决方案:

    function recursive_array_search($needle, $haystack, $currentKey = '') {
        foreach($haystack as $key=>$value) {
            if (is_array($value)) {
                $nextKey = recursive_array_search($needle,$value, $currentKey . '[' . $key . ']');
                if ($nextKey) {
                    return $nextKey;
                }
            }
            else if($value==$needle) {
                return is_numeric($key) ? $currentKey . '[' .$key . ']' : $currentKey . '["' .$key . '"]';
            }
        }
        return false;
    }
    

    这将导致

    [1][1][0]["CategoryID"]
    

    因为 CategoryID 也是多维数组中的一个键。

    如果你不想要这个,你可以调整函数来

    function recursive_array_search($needle, $haystack, $currentKey = '') {
        foreach($haystack as $key=>$value) {
            if (is_array($value)) {
                $nextKey = recursive_array_search($needle,$value, $currentKey . '[' . $key . ']');
                if ($nextKey) {
                    return $nextKey;
                }
            }
            else if($value==$needle) {
                return is_numeric($key) ? $currentKey . '[' .$key . ']' : $currentKey;
            }
        }
        return false;
    }
    

    【讨论】:

    • 谢谢大家,这行得通。抱歉这个愚蠢的问题,但如果我想打印获取的索引的值,我不能用$categories.$key 打印,它只会打印类别,然后是字面的字符串。
    • 我也想不通,有人吗?
    【解决方案2】:

    您忽略了对recursive_array_search 的内部调用的返回值。不要那样做。

    /*
     * Searches for $needle in the multidimensional array $haystack.
     *
     * @param mixed $needle The item to search for
     * @param array $haystack The array to search
     * @return array|bool The indices of $needle in $haystack across the
     *  various dimensions. FALSE if $needle was not found.
     */
    function recursive_array_search($needle,$haystack) {
        foreach($haystack as $key=>$value) {
            if($needle===$value) {
                return array($key);
            } else if (is_array($value) && $subkey = recursive_array_search($needle,$value)) {
                array_unshift($subkey, $key);
                return $subkey;
            }
        }
    }
    

    【讨论】:

    • 你好。在数组["name" => "class_test", "static" => true, "public" => true, "interface" => false] 中返回的是[0 => "static"],即只返回找到的第一个元素。用这个解决方案全部退回? [0 => "static", 1 => "public"]
    【解决方案3】:
    public static function unique(array $data, $key){
        $rez = [];
        foreach($data as $val){
            if(!isset($val[$key]) && is_array($val)){
                return self::unique($val, $key);
            }elseif( isset($val[$key]) ){
                $rez[] = $val[$key];
            }
        }
        return array_unique($rez);
    }
    

    【讨论】:

      【解决方案4】:
      function array_search_recursive( $search, $values = array(), $i = 0) {
          $match = false;
          var_dump($i, $search);
          $i++;
          foreach ( $values as $keyState => $val ) {
              var_dump($val == $search, 'expression');
              if ( $val == $search ) {
                  return $keyState;
              }
              if ( is_array( $val ) ) {
                  $match = array_search_recursive($search, $val, $i);
              }
              if ( $match !== false ) {
                  return $keyState;
              }
          }
      
          return false;
      }
      
      echo array_search_recursive($search, $canada)
      

      编辑:

      这将返回第一个密钥,测试$canada = array( 'Brazilia' => 'test1', "Alberta" => [ "Airdrie", "Brooks", "Camrose" ], "British Columbia" => [ "Abbotsford" => [ 'a', 'b', 'c' ], "Armstrong", "Castlegar" ], "Manitoba" => [ "Brandon", "Selkirk" ], 'Olanda' => 'test2' ); $search = "Selkirk";

      【讨论】:

        猜你喜欢
        • 2013-05-12
        • 2012-09-16
        • 1970-01-01
        • 1970-01-01
        • 2011-04-27
        • 2014-10-15
        • 2018-09-20
        • 1970-01-01
        相关资源
        最近更新 更多