在implode()中使用回调 [英] Using a callback in implode()

查看:80
本文介绍了在implode()中使用回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组,例如:

I have a multidimensional array, e.g.:

$values = array(
    'one' => array(
        'title' => 'Title One',
        'uri'   => 'http://example.com/one',
    ),
    'two' => array(
        'title' => 'Title Two',
        'uri'   => 'http://example.com/two',
    ),
);

...我想用 implode 函数,按顺序:

...and I'd like to parse through that with a closure in my implode function, à la:

$final_string = implode(' | ', function($values) {
    $return = array();

    foreach($values as $value)
        $return[] = '<a href="' . $value['uri'] . '">' . $value['title'] . '</a>';

    return $return;
});

但是,这种用法会产生传递了无效参数错误。我是否缺少语法,从而可以使用闭包?我正在使用PHP v5.3.16。

However, this usage yields an Invalid arguments passed error. Is there syntax that I'm missing which will make this use of closures possible? I'm using PHP v5.3.16.

推荐答案

Ashwin的答案是正确的。 原因如下:

Ashwin's answer is correct. Here's why:

当您将闭包直接传递给 implode 方法时-显式地想要第二个类型为 array 的参数,它实质上检查了 instanceof -因此是无效的参数。 内爆函数不会期望 mixed ,并且不知道执行闭包。

When you pass the closure directly to the implode method - which explicitly wants a second argument of type array, it essentially checks the instanceof - hence the invalid argument. The implode function does not expect mixed and doesn't know to execute the closure.

当您第一次将该函数分配给变量时,它使PHP首先评估该变量,最终将函数返回的值传递给 implode

When you first assign that function to a variable, it causes PHP to first evaluate that variable and it ends up passing the returned value from the function into implode.

在这种情况下,您将从函数中返回一个数组并将其传递给 implode -

In that case you're returning an array from the function and passing that into implode - that checks out.

编辑/添加:该匿名函数将是关闭实例

edit/adding: that anonymous function would be instanceof Closure.

Closure !== array

这篇关于在implode()中使用回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆