开发者

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 ne开发者_JS百科ed to loop each result and slugify it?

Thanks!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜