代码之家  ›  专栏  ›  技术社区  ›  Sam

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

  •  -1
  • Sam  · 技术社区  · 9 年前

    $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 a内回路 for $data Search_model :

    $result->select('country')
        ->from('results')
        ->like('country', $countries)
        ->order_by('country', 'ASC');
    $results = $result->get()->result_array();
    return $results;
    
    1 回复  |  直到 9 年前
        1
  •  0
  •   Sam    9 年前

    /* 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,带有图表和;JSON数据的打印:

    enter image description here

    非常感谢所有贡献者

    推荐文章