1

我想用逗号分解平台数据,例如:Windows、Mac、Linux。

我尝试了不同的选项,但仍然没有找到解决方案。所以我有一个问题,如何分解我用这段代码得到的数据?

<?php

$this->load->model('catalog/platform');

$query = $this->db->query("SELECT p2p.platform_id, p.parent_id FROM "
. DB_PREFIX . "platform p LEFT JOIN " . DB_PREFIX . "product_to_platform p2p
ON p.platform_id=p2p.platform_id WHERE product_id='" . $product_id . "' AND parent_id=0");

$prodplatforms = $query->rows;

foreach($prodplatforms as $prodplatform){

    $platform_id = $prodplatform['platform_id'];
    $platform_info = $this->model_catalog_platform->getPlatform($platform_id);
    $caturl = (HTTP_SERVER . 'index.php?route=product/platform&path=' . $platform_id);
    $str = $platform_info['name'];

        echo '<a href="' . $caturl . '">' . $str . '</a>';
}
?>
4

1 回答 1

0

您只需要进行一点编辑 - 而不是$str = $platform_info['name'];这样做:

// ...
$prodplatforms = $query->rows;

$platforms = array();

foreach($prodplatforms as $prodplatform){
    $platform_id = $prodplatform['platform_id'];
    $platform_info = $this->model_catalog_platform->getPlatform($platform_id);
    $caturl = (HTTP_SERVER . 'index.php?route=product/platform&path=' . $platform_id);
    $platforms[] = $platform_info['name'];
}

echo '<a href="' . $caturl . '">' . implode(', ', $platforms) . '</a>';

但现在看代码我猜你只想让每个平台名称链接到它的平台 URL...

查看您的代码,我猜您是在模板文件中执行所有这些操作。也许你只是把你的控制器、模型和模板中的代码放在一起——这没关系,但如果你真的在一个模板中做这一切,请将代码拆分到各个层:

控制器

$this->load->model('catalog/platform');
$prodplatforms = $this->model_catalog_platform->getPlatforms($product_id);

$this->data['platforms'] = array();

foreach($prodplatforms as $prodplatform){
    $platform_id = $prodplatform['platform_id'];
    $platform_info = $this->model_catalog_platform->getPlatform($platform_id);
    $caturl = (HTTP_SERVER . 'index.php?route=product/platform&path=' . $platform_id);
    $this->data['platforms'][] = '<a href="' . $caturl . '">' . $platform_info['name'] . '</a>';
}

型号( catalog/model/catalog/platform.php):

public function getPlatforms($product_id) {
    $query = $this->db->query("SELECT p2p.platform_id, p.parent_id FROM " . DB_PREFIX . "platform p LEFT JOIN " . DB_PREFIX . "product_to_platform p2p ON p.platform_id=p2p.platform_id WHERE product_id='" . $product_id . "' AND parent_id=0");

    return $query->rows;
}

查看模板

<div><?php echo implode(', ', $platforms); ?></div>
于 2013-05-09T08:30:33.230 回答