gpt4 book ai didi

php - 透明地展平数组

转载 作者:可可西里 更新时间:2023-11-01 12:31:04 24 4
gpt4 key购买 nike

读这个问题Merge and group by several arrays我有以下想法:当使用多级数组时,可能有重复的键,有一个函数可以迭代这样的数组,因为它是平面的,比如

foreach(flatten($deepArray) as $key => $val)....

关于如何编写 flatten() 有什么想法吗?有没有标准的解决方案?

(注意 flatten() 不能简单地返回一个新数组,因为重复键)。

最佳答案

RecursiveArrayIterator 的用法示例

$array = array( 
0 => 'a',
1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))),
2 => 'b',
3 => array('subA','subB','subC'),
4 => 'c'
);

foreach (return new RecursiveIteratorIterator(new RecursiveArrayIterator($array))
as $key => $val) {

printf(
'%s: %s' . "\n",
$key, $val
);
}

/* Output:
0: a
0: subA
1: subB
0: subsubA
1: subsubB
0: deepA
1: deepB
2: b
0: subA
1: subB
2: subC
4: c
*/

扩展 RecursiveIteratorIterator 以返回当前的键堆栈

class MyRecursiveIteratorIterator extends RecursiveIteratorIterator
{
public function key() {
return json_encode($this->getKeyStack());
}

public function getKeyStack() {
$result = array();
for ($depth = 0, $lim = $this->getDepth(); $depth < $lim; $depth += 1) {
$result[] = $this->getSubIterator($depth)->key();
}
$result[] = parent::key();
return $result;
}
}

foreach ($it = new MyRecursiveIteratorIterator(new RecursiveArrayIterator($array))
as $key => $val) {

printf('%s (%s): %s' . "\n", implode('.', $it->getKeyStack()), $key, $val);
}

/* Output:
0 ([0]): a
1.0 ([1,0]): subA
1.1 ([1,1]): subB
1.2.0 ([1,2,0]): subsubA
1.2.1 ([1,2,1]): subsubB
1.2.2.0 ([1,2,2,0]): deepA
1.2.2.1 ([1,2,2,1]): deepB
2 ([2]): b
3.0 ([3,0]): subA
3.1 ([3,1]): subB
3.2 ([3,2]): subC
4 ([4]): c
*/

另一个版本,这次不使用 RecursiveArrayIterator:

function flatten(array $array = array(), $keyStack = array(), $result = array()) {
foreach ($array as $key => $value) {
$keyStack[] = $key;

if (is_array($value)) {
$result = flatten($value, $keyStack, $result);
}
else {
$result[] = array(
'keys' => $keyStack,
'value' => $value
);
}

array_pop($keyStack);
}

return $result;
}

foreach (flatten($array) as $element) {
printf(
'%s: %s (depth: %s)' . "\n",
implode('.', $element['keys']),
$element['value'],
sizeof($element['keys'])
);
}

/*
0: a (depth: 1)
1.0: subA (depth: 2)
1.1: subB (depth: 2)
1.2.0: subsubA (depth: 3)
1.2.1: subsubB (depth: 3)
1.2.2.0: deepA (depth: 4)
1.2.2.1: deepB (depth: 4)
2: b (depth: 1)
3.0: subA (depth: 2)
3.1: subB (depth: 2)
3.2: subC (depth: 2)
4: c (depth: 1)
*/

关于php - 透明地展平数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7011451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com