Apply a callback to a multidimensional array
I have this in PHP:
$data = array("test"=>array("abc"=>"xyz"));
I want to append 'data:' with array values, so output will be 'data:xyz' for that $data array.
Its just a sample. How can I do this with multi dimension arrays. i.e; appending string with multi dimension array values ? Can I do with persistent values in same array so I can re-use this开发者_运维百科 ?
There's a PHP function that "[applies] a user function recursively to every member of an array" it's array_walk_recursive().
Here's an example for PHP 5.3 that uses a closure:
array_walk_recursive($data, function(&$str) { $str = "data:$str"; });
If you feel fancy, you can make it a function that accepts a configurable prefix, such as:
function prepend(&$v, $k, $prefix)
{
$v = $prefix . $v;
}
array_walk_recursive($data, 'prepend', 'data:');
Imagine that you want to apply a custom function to your array but only to an specific key => value pair, this is my improved version:
$data = array( "test" => array("abc" => "xyz", 'def'=> 2), 'test2' => array ( 'abc' => 'jkl', 'def' => 5) );
$keytochange = 'def';
$apply = 'md5';
$data = f($data,$keytochange,$apply);
function f($array, $keytochange, $apply)
{
foreach ($array as $key => $value)
{
if (is_array($value))
$array[$key] = f($value,$keytochange,$apply);
else
$array[$keytochange] = $apply( $value );
}
return $array;
}
print_r($data);
Output:
Array
(
[test] => Array
(
[abc] => xyz
[def] => c81e728d9d4c2f636f067f89cc14862c
)
[test2] => Array
(
[abc] => jkl
[def] => e4da3b7fbbce2345d7772b0674a318d5
)
)
If you don't care about human-readability and just want to serialise an Array for later use:
<?php
$data = Array("test" => Array("abc" => "xyz"));
$str = serialize($data);
echo 'data:' . $str;
print_r(unserialize($str));
// data:<some characters here>
// Array("test" => Array("abc" => "xyz"));
?>
If you're trying to modify the original array such that the text "data:" is prepended to every value in the Array on every level:
<?php
$data = Array("test" => Array("abc" => "xyz"));
function f($array) {
foreach ($array as $key => $value) {
if (is_array($value))
$array[$key] = f($value);
else
$array[$key] = "data:" . $value;
}
return $array;
}
$data = f($data);
print_r($data);
// Output: Array("test" => Array("abc" => "data:xyz"));
?>
To modify each item in an array, you can use the function array_map()
Example:
function Prepend($s)
{
return 'Data:'.$s;
}
$old_array = array('abc','def','ghi','xyz');
$new_Array = array_map('Prepend',$old_array);
var_dump($old_array);
var_dump($new_Array);
Output:
array
0 => string 'abc' (length=3)
1 => string 'def' (length=3)
2 => string 'ghi' (length=3)
3 => string 'xyz' (length=3)
array
0 => string 'Data:abc' (length=8)
1 => string 'Data:def' (length=8)
2 => string 'Data:ghi' (length=8)
3 => string 'Data:xyz' (length=8)
精彩评论