更細粒度的控制也許是可能的真(TM)遞歸陣列經由RecursiveIterator
接口遍歷和一些鍵過濾器和陣列轉換功能:
$needle = '0';
$array = [[1]];
$it = new KeyFilter(
new RecursiveIteratorIterator(
new MyRecursiveArrayIterator($array)
, RecursiveIteratorIterator::SELF_FIRST
)
, $needle
);
$result = iterator_to_array($it, FALSE);
var_dump($result);
提供的示例性結果爲:
array(2) {
[0] =>
array(1) {
[0] =>
int(1)
}
[1] =>
int(1)
}
完整代碼示例(Demo):
<?php
/**
* @link http://stackoverflow.com/q/19709410/367456
*/
Class MyRecursiveArrayIterator extends ArrayIterator implements RecursiveIterator
{
public function hasChildren()
{
$current = $this->current();
return is_array($current) && count($current);
}
public function getChildren()
{
return new self($this->current());
}
}
class KeyFilter extends RegexIterator
{
public function __construct(Iterator $iterator, $key)
{
parent::__construct(
$iterator, '/' . preg_quote($key) . '/', NULL, RegexIterator::USE_KEY
);
}
}
$needle = '0';
$array = [[1]];
$it = new KeyFilter(
new RecursiveIteratorIterator(
new MyRecursiveArrayIterator($array)
, RecursiveIteratorIterator::SELF_FIRST
)
, $needle
);
$result = iterator_to_array($it, FALSE);
var_dump($result);
array_walk_recursive或array_search和很多內置函數有沒有 –
@ArunKillu那是不相關的。我寫的函數有什麼問題? – dudemanbearpig
我們需要一個觸發錯誤的示例數組和函數參數。否則,不能複製問題。 – Sven