linkyndy
linkyndy

Reputation: 17920

CakePHP: Use Inflector Class over whole array

I need to use Inflector::slug() over all results fetched from my database, which are, of course, retrieved in an array. Is it possible somehow, or I'll need to loop each result and slugify it?

Thanks!

Upvotes: 1

Views: 1381

Answers (2)

Stoosh
Stoosh

Reputation: 2429

Depending on the array you can use array_walk or array_walk_recursive.

Something like this should work.

This is for 5.3+;

array_walk_recursive($posts, function(&$value) {
    $value = Inflector::slug($value);
});

If you wanted to limit it to a certain field you could also do something like this:

array_walk_recursive($posts, function(&$value, $key) {
if ($key == 'title') {
    $value = Inflector::slug($value);
  }
});

I haven't used Cake in a while but like Rob Wilkerson said, you might find that the Set class could make lighter work of this.

Upvotes: 0

Rob Wilkerson
Rob Wilkerson

Reputation: 41236

PHP's array_map() function might do what you need (although it assumes a simple indexed array).

array_map( 'Inflector::slug', $your_result )

If you're looking at something more complex, CakePHP's Set utility class may be helpful in a multi-step implementation.

I haven't tried this in a CakePHP context (i.e. mapping through a CakePHP class method), but I can't think of any reason it wouldn't work off the top of my head. Maybe it'll at least get you started.

Upvotes: 2

Related Questions