English 中文(简体)
在函数中处理一个数组,使用外部格式化处理。
原标题:Process an array in a function, with external formatting
  • 时间:2010-02-25 13:04:25
  •  标签:
  • php
  • php4

我想将一个数组传递到函数中,并在该函数中进行迭代。但我希望能够更改单个条目显示的方式。

假设我有一个复杂数组:

$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中实现这个?创意一些!

最佳回答

根据我的理解,您正在寻找一个带有函数参数的“注入”类型迭代器。在php中,注入迭代器是array_reduce,不幸的是它已经损坏了,所以您必须自己编写,例如。

function array_inject($ary, $func, $acc) {
 foreach($ary as $item)
  $acc = $func($acc, $item);
 return $acc;
}

定义一个回调函数,处理每个项目并返回累加器的值:

function boldify($list, $item) {
 return $list .= "<strong>$item</strong>";
}

其余的很容易:

$items = array( foo ,  bar ,  baz );
$res = array_inject($items,  boldify ,   );
print_r($res);
问题回答

你可以使用回调函数:

function item_title($item) {
    return $item[ title ];
}
function item_date($item) {
    return $item[ date ];
}
function prettyprint_item_date($item) {
    return pretty_print($item[ date ]);
}

function create_ul($items, $contentf= item_date , $titlef= item_title ) {
    $entries = array();
    foreach($items as $item) {
        $title = call_user_func($titlef, $item);
        $content = call_user_func($contentf, $item);
        $entries[] = create_li($title, $content);
    }
    return wrap_in_ul($entries);
}
...
$list = create_ul($items,  prettyprint_item_date );

PHP 5.3会是一个巨大的胜利,因为它支持匿名函数。





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签