2012-10-09 78 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函數返回找到值的「遍歷路徑」。 –