[英]Iterate multidimensional Array recursively and return same array structure and inserting new key/values in PHP
我正在嘗試編寫一個采用多維數組的片段,並在找到命名搜索鍵的同一級別插入一些鍵。 我不必依賴於數組的結構(但最多只能有5個級別)我不能使用傳遞引用,因此傳統的重復函數對這種方法沒有幫助。
我有兩個選項:SPL或遞歸,重新構造數組並在整個過程中改變它
使用SPL我似乎無法插入新值..
$a= new \ArrayObject($priceConfig);
$array = new \RecursiveArrayIterator($a);
$iterator = new \RecursiveIteratorIterator($array, \RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
if (is_array($value) && $key == 'prices') {
$iterator->offsetSet('myPrice',['amount'=>'1.00']);
}
}
print_r($a->getArrayCopy());
它不會將新密鑰插入所需的級別,但它會循環遍歷數組..我缺少什么?
重構數組並在嵌套數組中的鍵搜索中插入新值的遞歸函數有效,但我想使用迭代器來做到這一點。
function recursive( $input, $searchKey, $key=null) {
$holder = array();
if(is_array( $input)) {
foreach( $input as $key => $el) {
if (is_array($el)) {
$holder[$key] = recursive($el, $searchKey, $key);
if ($key == $searchKey) {
$holder[$key]['inertedPrice'] = "value";
}
} else {
$holder[$key] = $el;
}
}
}
return $holder;
}
INPUT(總是會有一些“價格關鍵和X級結構”)
[1] => Array
(
[1] => Array
(
[prices] => Array
(
[onePrice] => Array( [amount] => 10)
[finalPrice] => Array ([amount] => 10)
)
[key1] => value2
[key2] => value2
)
[2] => Array
(
[prices] => Array
(
[otherPrice] => Array([amount] => 20)
[finalPrice] => Array([amount] => 20)
)
[key] => value
)
)
)
產量
[1] => Array
(
[1] => Array
(
[prices] => Array
(
[onePrice] => Array( [amount] => 10)
[finalPrice] => Array ([amount] => 10)
[INSERTEDPrice] => Array([amount] => value)
)
[key1] => value2
[key2] => value2
)
[2] => Array
(
[prices] => Array
(
[otherPrice] => Array([amount] => 20)
[finalPrice] => Array([amount] => 20)
[INSERTEDPrice] => Array([amount] => )
)
[key] => value
)
)
)
您可以通過使用自定義迭代器邏輯擴展RecursiveArrayIterator
使用迭代器執行此操作:
class Foo extends RecursiveArrayIterator
{
public function getChildren()
{
if ($this->key() == 'prices') {
return new self(array_merge($this->current(), ['foo' => 'bar']));
} else {
return parent::getChildren();
}
}
}
你可以很容易地使用foreach循環和遞歸等基本工具來解決問題。 這是一個解決方案。
function mergeWithKey($targetKey, $new, array $array) {
foreach ($array as $key => $value) {
if ($key === $targetKey) {
$array[$key] = array_merge($array[$key], $new);
}
elseif (is_array($value)) {
$array[$key] = mergeWithKey($targetKey, $new, $value);
}
}
return $array;
}
// Example
$output = mergeWithKey('prices', array('INSERTEDPrice' => 'value'), $input);
簡單地說,當我們找到我們正在尋找的密鑰時,我們遍歷數組,然后我們合並新價格。 如果我們找到一個子數組,那么我們將新價格合並到該子數組中。
我通過將關鍵“價格”作為參數來做出一些努力來概括功能。 這可能仍然是一個不太可能看到重用的難以理解的功能。
有了幾個常見的算法,你可以很好地提升這個功能,而且你可以重用這些算法。 一種是使用鍵和值映射數組,另一種是將2D數組展平為1D數組。
function arrayMapWithKey(callable $f, array $array) {
$out = array();
foreach ($array as $key => $value) {
$out[$key] = $f($key, $value);
}
return $out;
}
function concat(array $array) {
if (empty($array)) {
return array();
}
else {
return call_user_func_array('array_merge', $array);
}
}
這些定義使您可以編寫替代解決方案。
function addPrice($name, $price, $data) {
return concat(arrayMapWithKey(
function ($k, $v) use ($name, $price) {
if ($k === 'prices') {
return array($k => array_merge($v, array($name => $price)));
}
elseif (is_array($v)) {
return array($k => addPrice($name, $price, $v));
}
else {
return array($k => $v);
}
},
$data
));
}
arrayMapWithKey
另一個公式是使用值復制鍵,然后使用常規array_map
。
function arrayWithKeys(array $array) {
$out = array();
foreach ($array as $key => $value) {
// in PHP arrays are often used as tuples,
// and here we have a 2-tuple.
$out[] = array($key, $value);
}
return $out;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.