2012-06-07 22 views
0

匹配條件可以說我有一個陣列如何濾波器陣列遞歸如果在PHP

array 
    array 
    key1 = 'hello im a text' 
    key2 = true; 
    key3 = '><><'; 
    array 
     array 
     key1 = 'hello another text' 
     key2 = 'im a text too' 
     key3 = false; 
     array 
      key1 = ')(&#' 
    array 
    key1 = 'and so on' 

我怎樣才能從上面的陣列類似下面?

array 1 =>'hello im a text'; 2 =>'你好另一個文本; 3 =>'我也是一個文本'; 4 =>'等等';

繼承人什麼香港專業教育學院做

$found = array(); 
function search_text($item, $key) 
{ 
    global $found; 
    if (strlen($item) > 5) 
    { 
     $found[] = $item; 
    } 
} 
array_walk_recursive($array, 'search_text'); 
var_dump($found); 

但不知何故,它不工作

回答

2

嘗試類似的措施:

function array_simplify($array, $newarray=array()) { //default of $newarray to be empty, so now it is not a required parameter 
    foreach ($array as $i) { 
     if (is_array($i)) { //if it is an array, we need to handle differently 
      $newarray = array_simplify($i, $newarray); // recursively calls the same function, since the function only appends to $newarray, doesn't reset it 
      continue; // goes to the next value in the loop, we know it isn't a string 
     } 
     if (is_string($i) && strlen($i)>5) { // so we want it in the one dimensional array 
      $newarray[] = $i; //append the value to $newarray 
     } 
    } 
    return $newarray; // passes the new array back - thus also updating $newarray after the recursive call 
} 

我的注意:我沒有測試過這一點,如果有錯誤,請告訴我,我會嘗試修復它們。

+0

我均值濾波陣列和使一個新的數組是一維數組值if(strlen($ item)> 5)在多維舊數組中 –

+0

因此它也必須是一個字符串呢?假設如此,我添加了if條款。 –

+0

我已將註釋添加到解釋它的代碼中。 –

0

像這樣的東西應該工作,

的情況我已經使用

if(is_string($son)) 

爲了得到一些成果,根據您的喜好

$input = <your input array>; 
$output = array(); 

foreach($input AS $object) 
{ 
    search_text($object,$output); 
} 

var_dump($output); 

function search_text($object, &$output) 
{ 
    foreach($object AS $son) 
    { 
     if(is_object($son)) 
     { 
      search_text($son, $output); 
     } 
     else 
     { 
      if(is_string($son)) 
      { 
       $output[] = $son; 
      } 
     } 
    } 
} 

說明你可以調整它:

search_text獲取2個參數:$object和由此產生的陣列$output

它檢查foreach對象的屬性,如果它是一個對象或不。

如果是則需要檢查本身對象,

否則search_text檢查該輸入是一個字符串,如果它是它被存儲到$output陣列