数据库中的Php数组没有得到所需的数组结构

时间:2015-08-21 14:48:24

标签: php arrays multidimensional-array while-loop

我通过从数据库中提取数据来构建多维数组有问题。 我的数据库中有一个销售代表(sr)列表。我运行查询并选择所有sr。 现在我必须创建这样的数组:

array (size=3)
  'Manoj' =>
    array (size=3)
      'mc_count' => 0
      'auto_count' => 0
      'in_count' => 0
  'Bharat' =>
    array (size=3)
      'mc_count' => 0
      'auto_count' => 0
      'in_count' => 0
  'Pradeep' =>
    array (size=3)
      'mc_count' => 0
      'auto_count' => 0
      'in_count' => 0

为了创建这个,我写了以下代码:

<?php
$sr_array=array();
$sr_sql= "select DISTINCT sr from sales_invoice";
$sr_query = mysqli_query($connection, $sr_sql);
while($sr_result = mysqli_fetch_assoc($sr_query)){
       $sr_array []= array($sr_result["sr"]=>array(“mc_count”,”auto_count”,”in_coun”);

        }
var_dump($sr_array);

?>

我得到了这个输出

array (size=9)
  0 =>
    array (size=1)
      'Manoj' =>
        array (size=3)
          'count_in_battery' => int 10
          'count_auto_battety' => int 0
          'count_indu_battery' => int 0
  1 =>
    array (size=1)
      'Bharat' =>
        array (size=3)
          'count_in_battery' => int 10
          'count_auto_battety' => int 0
          'count_indu_battery' => int 0
  2 =>
    array (size=1)
      'Pradeep =>
        array (size=3)
          'count_in_battery' => int 10
          'count_auto_battety' => int 0
          'count_indu_battery' => int 0

如果你看到输出我的数组有另外的索引

0 =>   //Unwanted Index
    array (size=1)
      'Manoj' =>

这在编程中造成了问题。如果你能帮助我。

1 个答案:

答案 0 :(得分:1)

试试这个:

$sr_array = array();
$sr_sql = "select DISTINCT sr from sales_invoice";
$sr_query = mysqli_query($connection, $sr_sql);

while($sr_result = mysqli_fetch_assoc($sr_query)){
    $sr_array[$sr_result["sr"]] = array(
        "mc_count" => 0,
        "auto_count" => 0,
        "in_coun" => 0
    );
}