Reputation: 7238
I need to replace all values in a multidimensional array by their respective key, but only if the value is not an array.
From:
array(
'key1' => array(
'key2' => array(
'key3' => 'val'
)
)
);
To:
array(
'key1' => array(
'key2' => array(
'key3'
)
)
);
Does anyone know a way to do this nicely?
Upvotes: 0
Views: 94
Reputation: 11467
This seems to do more or less what you want (fiddle):
<?php
function convert($arr) {
$ret = array();
foreach ($arr as $key => $value) {
if (is_array($value)) {
$ret[$key] = convert($value);
} else {
$ret[] = $key;
}
}
return $ret;
}
$test = array(
'key1' => array(
'key2' => array(
'key3' => 'val'
)
)
);
var_dump(convert($test));
Output:
array(1) {
["key1"]=>
array(1) {
["key2"]=>
array(1) {
[0]=>
string(4) "key3"
}
}
}
Upvotes: 1