使用php在数组中执行用户函数

str*_*ade 0 php arrays

我有一个包含比这个更多的项目的数组.这只是一个项目的示例:

[0] => Array
        (
            [id] => 6739380664
            [created_at] => 1260991464
            [text] => @codeforge thx for following
            [source] => web
            [user] => Array
                (
                    [id] => 90389269
                    [name] => Lea@JB
                    [screen_name] => Lea_JB
                    [description] => Fan of JB and Daourite singers!! (:
                    [location] => Germany
                    [url] => 
                    [protected] => 
                    [followers_count] => 33
                    [profile_image_url] => http://a3.01/Usher_und_JB_normal.jpg
                )

            [truncated] => 
            [favorited] => 
            [in_reply_to_status_id] => 
            [in_reply_to_user_id] => 18055539
        )
Run Code Online (Sandbox Code Playgroud)

我有一个功能

function parseLink($text)
{
  $text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $text);
  return $text;
}
Run Code Online (Sandbox Code Playgroud)

如何parseLink($text)text不需要循环的情况下为数组项应用我的函数?

它返回包含所有所有字段的整个数组,但是使用了modiefied数组字段 text?这不仅仅是项目$myarray[0]; 有更多的项目$myarray[1],$myarray[2],很快就会有.

Asa*_*aph 6

您可以通过两种不同的方式完成此任务:

1)您可以使用返回值parseLink()并在数组中重新分配变量:

$myText = parseLink($myArray[0]['text']);
$myArray[0]['text'] = $myText;
Run Code Online (Sandbox Code Playgroud)

2)您可以修改您的parseLink()函数以通过引用接受参数,这将导致它被修改到位:

function parseLink(&$text)
{
    $text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $text);
    return $text;
}

parseLink($myArray[0]['text']);
Run Code Online (Sandbox Code Playgroud)

  • @streetparade:不要担心循环的性能.循环将与PHP中的任何其他技术一样执行(它不执行任何可能加速的线程).PHP中的任何其他技术可能只是在引擎盖下使用循环(例如``array_map`).在任何情况下,CPU时间都不太可能是用PHP编写的典型数据库驱动的Web应用程序的瓶颈.如果您还没有真正测量过性能问题,请不要冒汗. (2认同)