使用codeigniter MVC动态生成PHP变量以从数据库填充morris.js图表​​

时间:2017-08-25 12:17:22

标签: php mysql arrays codeigniter for-loop

我正在使用codeigniter MVC最新版本并从我的数据库中生成一些报告,我的问题是,如果其中一个管理员添加了一个新的国家/地区,我必须进入CMS并手动添加该国家/地区。我试图通过从我的表创建变量然后将它们发送到我的输出表单来使这个动态,我当前生成一个变量数组,如下所示:

$vars = array();
$misc = 0;
$count = count($country_names);
for ($i = 0; $i <= $count; $i++) {
    ${"var$i"} = 0;
    array_push($vars, ${"var$i"});
}
array_push($vars, $misc);

这给了我以下数组:

Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 [12] => 0 [13] => 0 )

[13]$misc变量, 我现在需要遍历一个不同的表格并匹配各个国家来计算该县有多少人使用我们的服务的计数,我已经尝试了这一点,因为相关变量计数没有增加,所以我没有高兴:

$misc = 0;
$count = count($country_names);
for ($i = 0; $i <= $count; $i++) {
    ${"var$i"} = 0;
    array_push($vars, ${"var$i"});
    foreach ($data as $item) {
        if ($item['country'] === "UK") {
            ${"var$i"}++;
        } else {
            $misc++;
        }
        array_push($vars, ${"var$i"});
    }
}
array_push($vars, $misc);

这段代码仍然给我相同的数组输出,任何想法?我可以在foreach循环中使用for循环吗? $data是从Search_model发送的数组:

$result->select('country')
    ->from('results')
    ->like('country', $countries)
    ->order_by('country', 'ASC');
$results = $result->get()->result_array();
return $results;

1 个答案:

答案 0 :(得分:0)

这是我的解决方案,我使用了一个国家名称作为索引的数组,并将初始值指定为0.以下是我的控制器中的代码:

/* Create a string based on the countries array */
$new_country_names = array(); // An array of countries with numbers as indexes, EG: [0]=>Botswana etc
foreach ($country_names as $country) {
    $new_country_names[] = $country['name'];
}

/* Create a dynamic array of variables from the countries table, using the country name as the index EG: [UK]=>0 etc: */
$country_names_array = array(); // An array with country names as the index and 0 assigned to each one EG: [Botswana]=>0
foreach ($country_names as $country){
    $country_names_array[$country['name']] = 0;
}

/* Loop through each instance of the results table and create a count for all matching instances */
$misc = 0;
$countries_count = count($new_country_names);
$country_count = 0;
while($country_count < $countries_count) {
    foreach ($data as $item) {
        if ($item['country'] === $new_country_names[$country_count]) {
                                $country_names_array[$new_country_names[$country_count]] = $country_names_array[$new_country_names[$country_count]] + 1;
    } else {
            $misc++;
        }
    }
    $country_count++;
    }
$country_names_array = str_replace('_', ' ', $country_names_array); // Lose the underscores
$country_names_array = array_filter($country_names_array); // Filter out NULL values
$data = json_encode($country_names_array); // JSON encode the array to populate charts in the view

这是输出的SS与图表&amp; JSON数据的打印:

enter image description here

非常感谢所有贡献者