【问题标题】:PHP Adding database result to multidimensional arrayPHP将数据库结果添加到多维数组
【发布时间】:2013-02-28 10:08:39
【问题描述】:

我正在尝试在 PHP 中生成这样的多维数组:

$books =  array(

    "8" => array(   "my girl" => 2.5, 
                    "the god delusion" => 3.5,
                    "tweak" => 3, "the shack" => 4,
                    "the birds in my life" => 2.5,
                    "new moon" => 3.5),

    "14" => array(    "the last lecture" => 2.5, 
                      "the god delusion" => 3.5,
                      "the noble wilds" => 3, "the shack" => 3.5,
                      "the birds in my life" => 2.5, "new moon" => 1)
     );

来自这样的数据库表:

ID  value   title
------------------------------------------------------------------
8   5   Clara Callan
8   5   Where You'll Find Me: And Other Stories
8   5   The Middle Stories
8   5   Jane Doe
8   6   The Witchfinder (Amos Walker Mystery Series)
8   6   More Cunning Than Man: A Social History of Rats an...
8   7   Goodbye to the Buttermilk Sky
9   6   Beloved (Plume Contemporary Fiction)
12  10  If I'd Known Then What I Know Now: Why Not Learn f...
14  5   Mary-Kate & Ashley Switching Goals (Mary-Kate ...
14  5   Tell Me This Isn't Happening
14  6   Flood : Mississippi 1927
16  9   Airframe
17  7   Death in the Clouds
17  5   Bant/Spec.Last of the Breed
17  6   Piercing the Darkness
17  3   Prophet
19  7   Prague : A Novel

我已经尝试了几种方法,但我仍然无法弄清楚如何做到这一点。我在这里搜索了很多线程,但仍然没有人讨论这个问题。我是PHP的新手,所以我不太了解PHP中的数组概念。目前我的 PHP 代码是这样的:

        $result = mysql_query($mySelectQuery) or die("<br/><br/>".mysql_error());
        $books = array();
        while ($row = mysql_fetch_array($result)) 
        {
            $userID = $row{'User-ID'};
            $books[$userID] = array($row{'Book-Title'} => $row{'Book-Rating'},);
        }

该代码已经产生了与“我想要的”类似的结果,但它仍然替换了现有的书籍记录,所以最终每个用户的数组中只有一个书籍记录。我的问题是:

我怎样才能用我的查询结果填充一个像我这样格式化的多维数组?

提前一百万感谢您的回答。抱歉英语不好。

【问题讨论】:

    标签: php mysql database arrays


    【解决方案1】:

    在循环前添加:

    $books[$userID] = array();

    在循环内使用:

    $books[$userID][] = array($row{'Book-Title'} =&gt; $row{'Book-Rating'},);

    【讨论】:

      【解决方案2】:

      试试:

      $result = mysql_query($mySelectQuery) or die("<br/><br/>".mysql_error());
          $books = array();
          while ($row = mysql_fetch_array($result)) 
          {
              $userID = $row{'User-ID'};
              $books[$userID][$row{'Book-Title'}] = $row{'Book-Rating'};
          }
      

      这会将您的书名分配为数组键/索引,并将评级设置为其值。

      【讨论】:

        【解决方案3】:

        试试这个:

        $books[$userID][] = array($row{'Book-Title'} =&gt; $row{'Book-Rating'},);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-02-20
          • 2014-08-25
          • 2011-01-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-10
          相关资源
          最近更新 更多