2012-10-09 79 views
1
function array_searchRecursive($needle, $haystack, $strict=false, $path=array()) 
{ 
    if(!is_array($haystack)) { 
     return false; 
    } 

    foreach($haystack as $key => $val) { 

     if(is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path)) { 
      $path = array_merge($path, array($key), $subPath); 

      return $path; 
     } else if((!$strict && $val == $needle) || ($strict && $val === $needle)) { 

      $path[] = $key; 
      return $path; 
     } 
    } 
    return false; 
} 

做任何机构建议我具有相同的功能,可以在JavaScript中实现。 参考http://www.php.net/manual/en/function.array-search.php#68424array_search在javascript中递归

+3

超级真棒[PHP.js(http://phpjs.org/)项目有可能是你一个很好的起点功能:http://phpjs.org/functions/array_search/ –

回答

1

这可能会给你一个开始。没有经过彻底测试或高度优化,并假定使用jQuery(不应该是用其他实现替换jQuery实用程序功能的一个大问题)。

function searchArrayRecursive(needle, haystack, strict) { 

    function constructPath(needle, haystack, path, strict) { 
     if (!$.isArray(haystack)) { 
      return false; 
     } 
     var index; 
     for (index = 0; index < haystack.length; index++) { 
      var value = haystack[index]; 
      var currentPath = $.merge([], path); 
      currentPath.push(index); 

      if ((strict && value === needle) || (!strict && value == needle)) { 
       return currentPath; 
      } 
      if ($.isArray(value)) { 

       var foundPath = constructPath(needle, value, currentPath, strict); 
       if (foundPath) { 
        return foundPath; 
       } 
      } 
     } 

     return false; 
    } 


    return constructPath(needle, haystack, [], strict); 
} 

http://jsfiddle.net/b8TxJ/2/

+0

以扩展@Amitay的工作,这里是一个函数,当haystack包含数组和/或对象时返回路径:http://jsfiddle.net/jshado1/rKHXC/ – jacob

1

事实上,下划线(或可能更好的表演:lodash)是你的男人。 JavaScript在很大程度上是一种功能性语言,最新规范包含了下划线提供的大多数功能。对于browser-compat下划线仍然提供建议。

在您的情况最好的下划线的特点是:

var haystack = [ 
    {a: 1}, [{b: 2}, {c: 3}, [{d: 4}, {e: 5}, [{f: 6}, {g: 7}] ] ] 
], 
needle = 4; 

//Search 
var result = _(haystack).chain() //chain so we can keep underscoring 
    .flatten() //flatten the array 
    .find(function(o) { //find the first element that matches our search function 
    return _(o).chain() //chain so we can keep underscoring 
     .values() //get all object values as an array 
     .contains(needle) //see if any of our values contains the needle 
     .value(); //get out of the chain 
    }) 
    .value(); //get out of the chain 

//In short: 
var result = _(haystack).chain().flatten().find(function(o) { return _(o).chain().values().contains(needle).value(); }).value(); 

当然,你将有微调这一点,并实现你的$严格任何责任。

+0

它究竟返回什么?根据请求原始数组中的路径,还是简单的值?如果它返回值,似乎没有必要,因为我们正在寻找一个特定的值。 –

+0

我现在看到它将返回具有任何属性的第一个对象,其值是“针”。这是你的意思吗?因为引用的php函数返回找到值的“遍历路径”。 –