【问题标题】:Data from array into html combobox从数组到html组合框的数据
【发布时间】:2014-08-05 12:51:14
【问题描述】:

我在 Continente 类中有 2 个数组..都是公共的,我用 mysql 数据库中的记录填充数组。

class Continente{
    public $continente = array();
    public $tari= array();

}

我有一个对象,我调用方法将数据放入我的数组中。

$cont = new Continente;
$cont->setContinente();
$cont->setTari();

现在数组看起来像这样:

 Array ( 
[0] => Array ( [Id] => 1 [Nume] => Europa ) 
[1] => Array ( [Id] => 2 [Nume] => Asia ) 
[2] => Array ( [Id] => 3 [Nume] => Africa ) ) 

和:

Array 
( [0] => Array ( [Id] => 0 [Nume] => Romania [idContinent] => 1 [Populatie] => 2500 )
 [1] => Array ( [Id] => 0 [Nume] => Bulgaria [idContinent] => 1 [Populatie] => 2200 ) 
[2] => Array ( [Id] => 0 [Nume] => Estonia [idContinent] => 1 [Populatie] => 1100 ) 
[3] => Array ( [Id] => 0 [Nume] => Japonia [idContinent] => 2 [Populatie] => 5000 ) 
[4] => Array ( [Id] => 0 [Nume] => China [idContinent] => 2 [Populatie] => 4599 ) 
[5] => Array ( [Id] => 0 [Nume] => India [idContinent] => 2 [Populatie] => 6000 )
 [6] => Array ( [Id] => 0 [Nume] => Egipt [idContinent] => 3 [Populatie] => 444 ) )

现在我需要创建一个包含 3 个大陆的组合框,并且对于选择的每个大陆,我需要打印前 3 个国家/地区,按 'Populatie' 中的最大数字排序。

所以我可以选择大陆的国家...我有 Id=idContinent 。

现在我真的不知道该怎么做。在php中为此编写一个方法?因为我已经有了数组...或 html?

这是我尝试过的:

<html>
    <head></head>
    <body>
              <div>
                <br>
                <select>

                    <?php 
                        foreach($cont->tari as $val ){
                            echo '<option value="'.$val.'">'.$val.'</option>';
                        }
                    ?>
                </select>


            </div>

    </body>


</html>

【问题讨论】:

  • 您将公共属性与 setter 一起使用是否有原因?首先是公共财产?
  • 不。我想轻松访问 arryas。
  • 然后将它们设为私有并使用 getter。这是更好的做法。如果您将它们公开,那么 setter 方法将毫无意义。要回答您的问题,只需在输出之前对数组进行预排序。您有很多选择,请参阅数组文档:us2.php.net/manual/en/book.array.php
  • 我知道..但这现在并不重要。我可以稍后再做.. 现在我需要弄清楚如何将 ccontinents 放在一个选择框中,并按以下人口为每个大陆打印前 3 个国家。
  • 我使用setters方法从sql数据库中获取信息..并放入数组中。

标签: php html mysql arrays oop


【解决方案1】:

如果你能做到,我认为你可以清理你的数据结构,这会让你更容易完成你想做的事情。如果您像这样存储您的信息:

$data = array( Europa => array (Romania => 2500, 
                                Bulgaria => 2200,
                                Estonia => 1100 ),
               Asia => array ( Japonia => 5000,
                                China => 4599,
                                India => 6000 ) 
                                ...);

那么您也许可以消除对“ID”键的需求,而只需将数组索引用于您的 ID。

然后您可以使用arsort() 按值对子数组进行排序。像这样的:

foreach( $data as $cont => $pop_data ) {
     arsort( $pop_data );
}

然后为创建您的组合框,使用类似的代码:

foreach( $data as $cont => $pop_data ) {
    echo $cont . " Population Info:" . "<br>"; // or whatever
    foreach( $pop_data as $country => $pop ) {
         echo '<option value="'.$pop.'">'.$pop.'</option>';
     }
 }

【讨论】:

    猜你喜欢
    • 2012-09-17
    • 1970-01-01
    • 2013-01-10
    • 2019-03-06
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多