Php爆炸具有特定值的数组

时间:2014-07-21 07:03:40

标签: php arrays explode

我真的需要一些关于这段代码的帮助,而且我对PHP并不擅长。

以下是代码:

function projectAttr($number){
    global $clerk, $project;

    $projectid = $project['id'];
    $tags = array();
    $cleanUrls= (bool) $clerk->getSetting( "clean_urls", 1 );

    $getTags = $clerk->query_select ( "projects_to_tags", "DISTINCT tag", "WHERE projectid='$projectid' ORDER BY id ASC" );
    while ( $tag= $clerk->query_fetchArray( $getTags ) )
        {
            $tagset = explode('; ', $tag['tag']);
        }

    return html_entity_decode($tagset[$number]);
}

代码会爆炸一个字符串并将其放入一个数组中,我可以通过 projectAttr(0) 获取。但我想更具体地说明我想从字符串中得到什么。

这是我的字符串:

size='large'; caption='short text about post/project'; bgcolor='black'; color='white';

我想要的是,如果我写 projectAttr(size) ,它应该返回值 large ,依此类推。

这甚至可能吗?

谢谢,彼得

2 个答案:

答案 0 :(得分:0)

function projectAttr($number){
    $str= "size='large'; caption='short text about post/project'; bgcolor='black'; color='white';";
    $r = explode('; ', $str);
    foreach($r as $k=>$v) {
        $attr = explode('=', $v);
        $projectAttr[$attr[0]] = str_replace("'", "", $attr[1]);
    }
    return html_entity_decode($projectAttr[$number]);
}
echo projectAttr('size'); // large

答案 1 :(得分:0)

我会专门回答你想要的爆炸。您应修改projectAttr函数以查看此内容:

$items = explode('; ', $string);

$attr = array();
foreach($items as $item) {
    list($key, $val) = explode('=', $item);
    $attr[$key] = str_replace(array("'", ""), '',$val);
}

返回

Array (
    [size] => large
    [caption] => short text about post/project
    [bgcolor] => black
    [color] => white
)

EXAMPLE DEMO


所以修改你的功能看起来像这样:

function projectAttr($name) {
    global $clerk, $project;

    $projectid = $project['id'];
    $tags = array();
    $cleanUrls = (bool) $clerk->getSetting("clean_urls", 1);

    $getTags = $clerk->query_select("projects_to_tags", "DISTINCT tag", "WHERE projectid='$projectid' ORDER BY id ASC");
    while ($tag = $clerk->query_fetchArray($getTags)) {
        $items = explode('; ', $string);

        $attr = array();
        foreach ($items as $item) {
            list($key, $val) = explode('=', $item);
            $attr[$key] = str_replace(array("'", ""), '', $val);
        }
    }

    return html_entity_decode($attr[$name]);
}

这应该允许你这样称呼它:

projectAttr('size');