使用外部格式处理函数中的数组
我想将数组传递给函数并在该函数中迭代它。但我希望能够更改单个条目的显示方式。
假设我有一组复杂的对象:
$items = array($one, $two, $three);
现在我这样做:
$entries = array();
foreach($items as $item) {
$entries[] = create_li($item["title"], pretty_print($item["date"]));
}
$list = wrap_in_ul($entries);
我想在一行中完成上述操作:
$list = create_ul($items, $item["title"], pretty_print($item["date"]));
从 PHP4 开始有机会这样做吗?有创意!
I want to pass an array to a function and iterate through it in this function. But I would like to be able to change the way the single entries are displayed.
Suppose I have an array of complicated objects:
$items = array($one, $two, $three);
Right now I do:
$entries = array();
foreach($items as $item) {
$entries[] = create_li($item["title"], pretty_print($item["date"]));
}
$list = wrap_in_ul($entries);
I would like to do the above in one line:
$list = create_ul($items, $item["title"], pretty_print($item["date"]));
Any chance of doing that as of PHP4? Be creative!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据我的理解,您正在寻找带有功能参数的“注入”类型迭代器。在php中,注入迭代器是array_reduce,不幸的是它被破坏了,所以你必须编写自己的迭代器,例如
定义一个回调函数来处理每个项目并返回累加器值:
剩下的很简单:
from my understanding, you're looking for an "inject" type iterator with a functional parameter. In php, inject iterator is array_reduce, unfortunately it's broken, so you have to write your own, for example
define a callback function that processes each item and returns accumulator value:
the rest is easy:
您可以使用回调:
PHP 5.3 将是一个巨大的胜利,因为它支持匿名函数。
You could use callbacks:
PHP 5.3 would be a big win here, with its support for anonymous functions.