我需要将一个关联数组键提取到一个字符串中,然后用“/”或任何字符/符号进行内爆。
例如:
$array = array([key1] =>
array([key11] =>
array([key111] => 'value111',
[key112] => 'value112',
[key113] => 'value113',
),
),
);
我需要一个如下数组的输出:
array([0] => 'key1/key11/key111',[1] => 'key1/key11/key112', [2] => 'key1/key11/key112');
答案 0 :(得分:1)
适用于不同深度的数组:
function getKeys($array, $prefix='', $separator = '/') {
$return = array();
foreach($array as $key => $value) {
if (!is_array($value)) $return[] = $prefix . $key;
else $return = array_merge($return, getKeys($value, $prefix . $key . separator), $separator);
}
return $return;
}
$keys = getKeys($array, '', '#');
参见在线小提琴http://ideone.com/krU4Xn
答案 1 :(得分:1)
我已根据here编辑了一个答案,并提出了以下代码。
function listArrayRecursive($someArray, &$outputArray, $separator = "/") {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($someArray), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $k => $v) {
if (!$iterator->hasChildren()) {
for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) {
$p[] = $iterator->getSubIterator($i)->key();
}
$path = implode($separator, $p);
$outputArray[] = $path;
}
}
}
$outputArray = array();
listArrayRecursive($array, $outputArray);
print_r($outputArray);
<强>输入:强>
Array
(
[key1] => Array
(
[key11] => Array
(
[key111] => value111
[key112] => value113
[key113] => value113
)
)
)
<强>输出:强>
Array
(
[0] => key1/key11/key111
[1] => key1/key11/key112
[2] => key1/key11/key113
)
答案 2 :(得分:0)
$mapArray = array();
$symbol = '/';
foreach($array as $k =>$v)
foreach($v as $k1 =>$v1)
foreach($v1 as $k2 =>$v2)
$mapArray[] = $k.$symbol.$k1.$symbol.$k2;
这显然只适用于这种特殊情况,如果需要更通用的话可以做到,但我认为这应该让你开始。