在过去的几天里,我一直在思考如何处理多维数组中的键,但我只是想不通。问题是,我不知道数组的深度-我希望我的代码能够处理任何深度的数组。
数组本身来自“高级自定义字段”,但这并不是太重要。我需要遍历数组,在以field_
开头的每个数组键上运行一个函数(将其从field_*
转换为诸如post_title
之类的专有名称),并重建具有相同结构和值的数组(尽管顺序并不重要)。数组如下所示:
array (size=12)
'field_5b23d04fef8a6' => string '' (length=0)
'field_5b23d04fefa99' => string '' (length=0)
'field_5b23d04fefe85' => string '' (length=0)
'field_5b23d04ff0077' => string '' (length=0)
'field_5b23d04ff026c' => string '' (length=0)
'field_5b23d0bdb3c1a' => string 'Version 1' (length=9)
'field_5b23d0f48538b' => string '' (length=0)
'field_5b23d0f485772' => string '' (length=0)
'field_5b23d0d52be2d' => string '' (length=0)
'field_5b5ed10a6a7bc' => string '' (length=0)
'field_5b5ed10a6bcf5' =>
array (size=1)
0 =>
array (size=1)
'field_5b5ed10acd264' =>
array (size=1)
0 =>
array (size=6)
'field_5b5ed10b0c9ca' => string '0' (length=1)
'field_5b5ed10b0cce2' => string 'TEST1234' (length=8)
'field_5b5ed10b0d0fd' => string 'Download title' (length=14)
'field_5b5ed10b0d4e2' => string 'EN' (length=2)
'field_5b5ed10b0d72e' => string 'A00' (length=3)
'field_5b5ed10b0df27' => string '887' (length=3)
'field_5b23d088500a4' => string '' (length=0)
处理此问题的最佳方法是什么?我已经看过递归函数和ResursiveArrayIterator,但是我发现的所有例子都不够接近,无法让我知道需要什么。
答案 0 :(得分:1)
如果发现以下嵌套数组,则可以递归调用同一函数:
Mode=OneWayToSource
所以我一直在研究,据我所知,callbacks没有用于递归的包装器功能,所以它是:
@font-face {
font-family: 'Wremena';
src: url('./fonts/Wremena Light.woff') format('woff'),
url('./fonts/Wremena Light.woff2') format('woff2'),
url('./fonts/Wremena Light.ttf') format('truetype'),
url('./fonts/Wremena Light.otf') format('opentype');
font-weight: normal;
font-style: normal;
}
或者例如:
.name {
font-family: 'Wremena', serif;
font-weight: lighter;
font-size: 2em;
line-height: 1em;
}
答案 1 :(得分:0)
您可以执行以下操作:
$arr = [
'a',
'b',
'c',
[
'd',
'e',
'f',
[
'g',
'h',
'i',
],
],
];
class MyIterator
{
public function iterate( $array )
{
foreach ( $array as $a ) {
if ( is_array( $a ) ) {
$this->iterate($a);
} else {
echo $a;
}
}
}
}
$iterator = new MyIterator();
$iterator->iterate($arr);
它打印此:
abcdefghi
答案 2 :(得分:0)
您可以像这样递归遍历数组
function recursiveWalk($array, callable $x)
{
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$result[$key] = recursiveWalk($value, $x);
} else {
$result[$key] = $x($value);
}
}
return $result;
}
例如:
$array = [
"aaa" => 1,
"sub1" => [
"xxx" => 2,
"sub2" => [
"yyy" => 3,
"ttt" => 4
]
]
];
print_r(recursiveWalk($array, function ($x) {
return $x + 1;
}));
Array
(
[aaa] => 2
[sub1] => Array
(
[xxx] => 3
[sub2] => Array
(
[yyy] => 4
[ttt] => 5
)
)
)