Tobiasz Cudnik

Posts Tagged ‘arrays’

Modify arrays easily using BAM – BulkArrayModifier

In Chainable, Ideas on 30.12.2008 at 22:46

Have you ever needed to modify certain fields in deeply nested array structure ? I’ve had such tasks writing CakePHP views quite often. Tried to use Set, but it only extracts data. When you modify it, you can use it standalone, but not with rest of the data it was stick to before extracting. That’s why i’ve always wanted to write something what will make this process cleaner and more natural, removing the need to write redundant code.

That’s why one evening i sat down and here it is – BulkArrayModifier. Standalone, chainable, ~120 lines class which extracts array’s content via references. It utilizes callbacks as much as possible. Consider this example:

// get all comments from all posts
bam($posts)->all()->key('Comment')->all()->each('modifyTitle');
// and use this callback to modify each one
function modifyTitle($comment) {
  $comment['title'] = "<a>{$comment['title']}</a>";
  return $comment;
}

There is also one-method query, like this:

bam($posts)->path('*.Comment.*')->each('modifyTitle');

You can also apply several callbacks to one bam() object

bam($posts)->path('*.Comment.*')->each('modifyTitle')->reset()
  ->path('*.Post.author')->each('modifyAuthor');

Read the rest of this entry »

Follow

Get every new post delivered to your Inbox.