0

好的,所以我有一个“TLD”列表,我想循环并在 PHP 中创建一个图表。

我想查找每个 TLD 并使用该 TLD 的名称作为变量。即 yahoo.com 将是 $yahoocom,这样我就可以为数据库中的所有“TLD”创建图表。

我的代码:

        $tld = $this->Report->getTLDs();

    foreach($tld as $row){

        $tld = str_replace('.','', $row['inboxer_tlds']['tld_name'] . 'openchart'); //yahoocomopenchart

        $$tld = new GoogleCharts();

        $$tld->type("PieChart");
        $$tld->options(array('title' => "Opens Stats for ". $row['inboxer_tlds']['tld_name']));
        $$tld->columns(array(
            'tld' => array(
                'type' => 'string',
                'label' => 'tld'
            ),
            'number' => array(
                'type' => 'number',
                'label' => 'number'
            )
        ));

        $$tld->addRow(array('tld' => $row['inboxer_tlds']['tld_name'], 'number' => $junk['0']['0']['COUNT(*)']));

        $this->set(compact('tld'));
    }

首先,我使用的变量变量对吗?我收到此错误:

get_class() 期望参数 1 是对象

我“认为” $$tld 应该等于 $yahoocom ?

最后,是否可以在视图中“设置”?通常你只会做 set(compact('variable')),但由于没有美元符号,......我不知道?

4

1 回答 1

0

这对我来说有点奇怪,我会放弃它并使用带有 TLD 名称的数组作为键。

像这样的东西(请注意,我还更改了变量名称和其他内容以使其更清洁):

$tlds = $this->Report->getTLDs();

$charts = array();
foreach($tlds as $tld) {

    $name = $tld['inboxer_tlds']['tld_name'];

    $chart = new GoogleCharts();

    $chart->type('PieChart');
    $chart->options(array('title' => 'Opens Stats for ' . $name));
    $chart->columns(array(
        'tld' => array(
            'type' => 'string',
            'label' => 'tld'
        ),
        'number' => array(
            'type' => 'number',
            'label' => 'number'
        )
    ));

    $chart->addRow(array('tld' => $name, 'number' => $junk['0']['0']['COUNT(*)']));

    $charts[$name] = $chart;
}

$this->set(compact('charts'));

因此,您最终会得到charts视图中命名的变量,其中包含如下结构:

Array
(
    [google.com] => GoogleCharts Object
    [yahoo.com] => GoogleCharts Object
    ...
)

为了完整起见,您可以compact通过将名称作为变量传递来使用动态变量,即

compact($tld)

set()您也可以手动创建数组:

$this->set(array($tld => $$tld));

或者传递两个参数,第一个是名称,第二个是值:

$this->set($tld, $$tld);
于 2013-09-26T23:22:09.880 回答