How do I use a recursive array iterator to process a multidimensional array?

前端 未结 1 460
萌比男神i
萌比男神i 2021-02-04 16:22

I\'m trying to get something like this working:

function posts_formatter (&$posts){
    foreach ($posts as $k => $v){

        if (is_array($v)){

                


        
1条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 17:01

    Ok, here is a quick something for you to figure out:

    $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'
         )
    ));
    

    The main idea is to influence how the Iterator returns the current element. Iterators are stackable, so you should use a RecursiveArrayIterator and wrap it into a RecursiveIteratorIterator. To achieve custom functionality, you can either subclass the RecursiveIteratorIterator (as shown below) or use additional iterators to decorate the 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;
        }
    }
    

    Then you simply foreach over the iterator

    $it = new PostFormatter(new RecursiveArrayIterator($data));
    foreach($it as $key => $post) {
        echo "$key: $post", PHP_EOL;
    }
    

    and get

    title: How To Work With Iterators
    title: Introduction To Iterators
    email: johndoe@example.com
    title: Extending Iterators
    email: janedoe@example.com
    

    You can try to get the array back from the with iterator_to_array or iterator_apply functions. However, to get the values reapplied to the original array structure, you dont need an iterator:

    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);
    

    Note: exchange Lambda with Function name when using PHP<5.3

    0 讨论(0)
提交回复
热议问题