1

I have this little function running at my wordpress site. But I need to add a bit of data to it. Hope I can get help.

Function array_to_comma($data)
{

    if (is_array($data) and count($data) > 0) 
    {
        $data = implode(', ', $data);
        return $data;
    }
}

Which outputs this:

Some Data, Some Data, Some Data

But I want to add some html code to it, a span, but I do not know how. So that it would appear like this in the source code of a rendered page. I see that it already adds a comma, but I cannot figure out to get to add more data then just the comma to appear at start and end. like this:

<span special="codes">Some Data</span>, <span special="codes">Some Data</span>, <span special="codes">Some Data</span>

Thank you in anticipation of a great help!. I am a php noob :)

EDIT: I have successfully used this code below. from the answer from elclanrs.

function array_to_comma($data)
{
    if (is_array($data) and count($data) > 0) {
        $data = '<span special="code">'
            . implode('</span>,<span special="code">', $data)
            .'</span>';
        return $data;       
    }
}
4

3 回答 3

5

这应该有效:

$result = '<span>'. implode('</span>,<span>', $data) .'</span>';

您可以这样做来添加属性:

$span = '<span special="codes">';
$result = $span . implode('</span>,'. $span, $data) .'</span>';

编辑:它可以被更多地抽象以被重用:

function wrapInTag($arr, $tag='span', $atts='', $sep=',') {
  return "<$tag>". implode("</$tag>$sep<$tag $atts>", $arr) ."</$tag>";
}

// Printing a list
echo '<ul>'. wrapInTag(['one','two','three'], 'li', 'class="item"') .'</ul>';
于 2013-08-25T04:08:44.327 回答
1

首先添加字符串:

foreach ($data as $key=>$val){
    $data[$key] = '<span special="codes">'.$val.'</span>';
}

然后执行你的内爆来得到逗号。

于 2013-08-25T04:04:03.383 回答
0

或者你可以在你内爆后修复它:

Function array_to_comma($data)
{    
    if (is_array($data) and count($data) > 0) 
    {            
        foreach($data as $elem)
        {
            $elem = "<span special=\"codes\">" . $elem . "</span>"
        }   
        $data = implode(', ', $data); 
        return $data;    
    }
}
于 2013-08-25T04:04:30.077 回答