【问题标题】:Error in adding data to multi-dimensional array in php在php中向多维数组添加数据时出错
【发布时间】:2013-11-23 15:03:36
【问题描述】:

我想从数据库中读取数据,并将其放入多维数组中。 我不知道将来自数据库的行数,当我尝试向多维数组添加新行时出现以下错误

Warning: array_push() [function.array-push]: First argument should be an array in C:\AppServ\www\web\commands\changeservice.php on line 101

这是我的代码

function preparenewservices()
    {

                $managername = $_SESSION['managername'];

                $sqls = "select s.*,m.* from rm_allowedmanagers m inner join rm_services s on s.srvid = m.srvid where m.managername = '$managername' ";


                $sql = mysql_query($sqls);


                 $newservices =  array();


                    while($row = mysql_fetch_array($sql))
                  {
                        $nsrvid = $row['srvid'];
                        $nsrvname = $row['srvname'];                        
                        $nunitprice = $row['unitprice'];
                        $nunitpricetax = $row['unitpricetax'];

                        $ntotal = $nunitprice + $nunitpricetax;

                        $newservice = array($nsrvid, $nsrvname , $ntotal); 

                        array_push ($newservices[count($newservices)], $newservice);

               }

    }

【问题讨论】:

    标签: php sql multidimensional-array


    【解决方案1】:

    试试这个:

    array_push ($newservices, $newservice);
    

    代替:

    array_push ($newservices[count($newservices)], $newservice);
    

    因为现在您将array_push 的第一个参数传递给integer 值而不是array

    【讨论】:

      【解决方案2】:

      那是因为$newservices[count($newservices)] 不是数组

      在此处阅读文档array_push

      只是为了修复错误,您可以这样做

      $newservices[count($newservices)] = array();
      array_push ($newservices[count($newservices)], $newservice);
      

      【讨论】:

      • @str 同意。它将向用户阐明错误,他可以根据自己的要求更改代码。
      【解决方案3】:

      尝试替换此代码

      array_push($newservices[count($newservices)], $newservice);

      $newservices[count($newservices)] = $newservice;

      【讨论】:

      • 数组是零索引,不需要加一。
      【解决方案4】:

      将元素/数组添加到另一个数组的最简单方法是:

      $newservices[] = $newservice;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-10
        • 2017-09-04
        • 2011-03-07
        • 2016-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多