我需要位方向来重命名内部深度未知的内部子键。原始数组是通过id和parent_id关系创建的父子多维数组。这是数组的一个例子
$testArray = array (
"name" => "Test name",
"someValue1" => 834.69,
"someMoreValue" => 33.4,
"someCode" => 6668,
"child" => array
(
array
(
"name" => "Some name",
"someValue1" => 471.05,
"someMoreValue" => 18.84,
"someCode" => 7064,
"child" => array
(
array
(
"name" => "Yet another name",
"someValue1" => 438.62,
"someMoreValue" => 17.56,
"someCode" => 7065
),
array
(
"name" => "Da name",
"someValue1" => 4444,
"someMoreValue" => 44,
"someCode" => 7044
)
)
),
array
(
"name" => "name",
"someValue1" => 2222,
"someMoreValue" => 22,
"someCode" => 7022
)
)
);
到目前为止,这是我的尝试,我只能重命名第一级儿童。
function keyprefix($keyprefix, $keyprefix2, Array $array) {
foreach($array as $k=>$v){
$array[$keyprefix.'-'.$k.'-'.$keyprefix2] = $v;
unset($array[$k]);
}
return $array;
}
function test($array) {
$newArr = array();
foreach ($array as $key => $value) {
// $newArr[] = is_array($value) ? test($value) : $value;
// $newArr[] = is_array($value) ? $array : array_merge( keyprefix("$name","Alt Danışman", $array[$key]) );
$index = 0;
$name = $array['name'];
if (is_array($value)) {
//if (is_array($value)) {
// test($value);
//}
$newArr[$key] = array_merge(
keyprefix("$name","Under Child", $array[$key])
);
}
else {
$newArr[$key] = $value;
}
}
return $newArr;
}
echo highlight_string(var_export(test($testArray), true));
关于如何解决这个问题的任何想法?我觉得我很接近,只需要在正确的道路上提供一些指导即可。我已经看到了许多堆栈溢出等示例,但需要一些帮助。我知道递归还不是我的最佳技能。
答案 0 :(得分:4)
function TryRenameChildren(array $array)
{
if(isset($array['child']))
{
$array['child'] = keyprefix($array['name'], 'prefix2', $array['child']);
foreach($array['child'] as $key => $value)
if(is_array($value))
$array['child'][$key] = TryRenameChildren($value);
}
return $array;
}
$testArray = TryRenameChildren($testArray);