I’m trying to get something like this working:
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;
}
}
}
}
It will correctly go through the array and format the values but I can’t get it to return them. I’ve played around with removing the & from the function declaration and adding a return at the end but it won’t do anything.
Additionally, I’m thinking perhaps using a RecursiveArrayIterator might be the way to go. However, despite the presence of a book right in front of me with a chapter on SPL Iterators its examples are useless towards being able to achieve what I’m trying to. How would I go about implementing one?
Edit:
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'
)
Ok, here is a quick something for you to figure out:
The main idea is to influence how the
Iteratorreturns thecurrentelement. Iterators are stackable, so you should use aRecursiveArrayIteratorand wrap it into aRecursiveIteratorIterator. To achieve custom functionality, you can either subclass theRecursiveIteratorIterator(as shown below) or use additional iterators to decorate theRecursiveIteratorIterator:Then you simply
foreachover the iteratorand get
You can try to get the array back from the with
iterator_to_arrayoriterator_applyfunctions. However, to get the values reapplied to the original array structure, you dont need an iterator:Note: exchange Lambda with Function name when using PHP<5.3