bcm*_*cfc 8 php recursion iterator multidimensional-array
我想尝试这样的工作:
function posts_formatter (&$posts){
foreach ($posts as $k => $v){
if (is_array($v)){
posts_formatter($v);
}else{
switch (strtolower($k)){
# make email addresses lowercase
case (strpos($k, 'email') !== FALSE):
$posts[$k] = strtolower($v);
break;
# make postcodes uppercase
case (strpos($k, 'postcode') !== FALSE):
$posts[$k] = strtoupper($v);
break;
# capitalize certain things
case (strpos($k, 'line1') !== FALSE):
case (strpos($k, 'line2') !== FALSE):
case (strpos($k, 'line3') !== FALSE):
case (strpos($k, 'forename') !== FALSE):
case (strpos($k, 'surname') !== FALSE):
$posts[$k] = capitalize($v);
break;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
它将正确地通过数组并格式化值,但我不能让它返回它们.我已经玩过了&从函数声明中删除并在最后添加一个返回但它不会做任何事情.
另外,我在考虑使用一种RecursiveArrayIterator可能的方式.然而,尽管我面前有一本关于SPL迭代器的章节,但它的例子对于实现我正在尝试的目标毫无用处.我将如何实施一个?
编辑:
array (
'user' =>
array (
'title' => 'Mr.',
'forename' => 'lowercase',
'surname' => 'name',
'businessName' => 'some dude',
'telephone' => '07545464646',
'postcode' => 'wa1 6nj',
'line1' => 'blergh road',
'line2' => 'randomLY cApitaLIzed wOrds',
'line3' => '',
),
'email' => 'CAPITALIZED@BLERGH.com',
'address' =>
array (
'postcode' => 'ab1 1ba',
'line1' => 'test road',
'line2' => 'testville',
'line3' => 'testshire',
),
'date' => '2010-09-30'
)
Run Code Online (Sandbox Code Playgroud)
Gor*_*don 19
好的,这是一个快速的东西让你弄清楚:
$data = array(
'title' => 'how to work with iterators',
'posts' => array(
array(
'title' => 'introduction to iterators',
'email' => 'JohnDoe@example.com'
), array(
'title' => 'extending iterators',
'email' => 'JaneDoe@example.com'
)
));
Run Code Online (Sandbox Code Playgroud)
主要思想是影响元素的Iterator返回方式current.迭代器是可堆叠的,所以你应该使用a RecursiveArrayIterator并将其包装成一个RecursiveIteratorIterator.要实现自定义功能,您可以子类化RecursiveIteratorIterator(如下所示)或使用其他迭代器来装饰RecursiveIteratorIterator:
class PostFormatter extends RecursiveIteratorIterator
{
public function current()
{
$current = parent::current();
switch($this->key()) {
case 'email':
$current = strtolower($current);
break;
case 'title':
$current = ucwords($current);
break;
default:
break;
}
return $current;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你只需要foreach通过迭代器
$it = new PostFormatter(new RecursiveArrayIterator($data));
foreach($it as $key => $post) {
echo "$key: $post", PHP_EOL;
}
Run Code Online (Sandbox Code Playgroud)
得到
title: How To Work With Iterators
title: Introduction To Iterators
email: johndoe@example.com
title: Extending Iterators
email: janedoe@example.com
Run Code Online (Sandbox Code Playgroud)
您可以尝试从with iterator_to_array或iterator_apply函数中恢复数组.但是,要将值重新应用于原始数组结构,您不需要迭代器:
array_walk_recursive($data, function(&$val, $key) {
switch($key) {
case 'title': $val = ucwords($val); break;
case 'email': $val = strtolower($val); break;
default: break;
}
});
print_r($data);
Run Code Online (Sandbox Code Playgroud)
注意:使用PHP <5.3时,使用函数名交换Lambda