i need to write function that searches & replaces key in multi-dimensional array in following manner:
input array:
[0] => Array
(
[Foo] => sometext
[Foo2] => Array
(
[lorem] => 1
[Avatar2] => Array
(
[meta_key] => avatar2
[meta_value] => Array
(
[small] => 65606449bb5b6d10c2dfce9ecb88fdbd-24-small.jpeg
开发者_StackOverflow [medium] => 65606449bb5b6d10c2dfce9ecb88fdbd-45-medium.jpeg
[large] => 65606449bb5b6d10c2dfce9ecb88fdbd-75-large.jpeg
[source] => 65606449bb5b6d10c2dfce9ecb88fdbd.jpg
)
)
)
[Avatar] => Array
(
[meta_key] => avatar
[meta_value] => Array
(
[small] => 65606449bb5b6d10c2dfce9ecb88fdbd-24-small.jpeg
[medium] => 65606449bb5b6d10c2dfce9ecb88fdbd-45-medium.jpeg
[large] => 65606449bb5b6d10c2dfce9ecb88fdbd-75-large.jpeg
[source] => 65606449bb5b6d10c2dfce9ecb88fdbd.jpg
)
)
)
[1] => Array
(
[Wallpaper] => Array
(
[meta_key] => wallpaper
[meta_value] => Array
(
[small] => 65606449bb5b6d10c2dfce9ecb88fdbd-24-small.jpeg
[medium] => 65606449bb5b6d10c2dfce9ecb88fdbd-45-medium.jpeg
[large] => 65606449bb5b6d10c2dfce9ecb88fdbd-75-large.jpeg
[source] => 65606449bb5b6d10c2dfce9ecb88fdbd.jpg
)
)
)
output array should look like this:
[0] => Array
(
[Foo] => sometext
[Foo2] => Array
(
[lorem] => 1
[Avatar2] => Array (
[small] => 65606449bb5b6d10c2dfce9ecb88fdbd-24-small.jpeg
[medium] => 65606449bb5b6d10c2dfce9ecb88fdbd-45-medium.jpeg
[large] => 65606449bb5b6d10c2dfce9ecb88fdbd-75-large.jpeg
[source] => 65606449bb5b6d10c2dfce9ecb88fdbd.jpg
)
)
[Avatar] => Array
(
[small] => 65606449bb5b6d10c2dfce9ecb88fdbd-24-small.jpeg
[medium] => 65606449bb5b6d10c2dfce9ecb88fdbd-45-medium.jpeg
[large] => 65606449bb5b6d10c2dfce9ecb88fdbd-75-large.jpeg
[source] => 65606449bb5b6d10c2dfce9ecb88fdbd.jpg
)
)
[1] => Array
(
[Wallpaper] => Array
(
[small] => 65606449bb5b6d10c2dfce9ecb88fdbd-24-small.jpeg
[medium] => 65606449bb5b6d10c2dfce9ecb88fdbd-45-medium.jpeg
[large] => 65606449bb5b6d10c2dfce9ecb88fdbd-75-large.jpeg
[source] => 65606449bb5b6d10c2dfce9ecb88fdbd.jpg
)
)
as you see, i need to reformat meta_key/meta_value part. Any suggestions (raw PHP or using CakePHP Set Class) are welcome:)
You'll defenetly need to use recursion for this:
function replace_inner_meta_keys($arr) {
if (array_key_exists('meta_value', $arr)) {
// return meta value instead of original array
return $arr['meta_value'];
}
else {
foreach ($arr as $key => $value) {
if (is_array($value)) {
// travel through array recursivly
$arr[$key] = replace_inner_meta_keys($value);
}
}
return $arr;
}
}
精彩评论