在php中将数据添加到多维数组时出错


Error in adding data to multi-dimensional array in php

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

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);
               }
    }

试试这个:

array_push ($newservices, $newservice);

而不是:

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

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

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

此处阅读文档array_push

只是为了修复错误,你可以做这个

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

尝试替换此代码

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

带有

$newsservices[count($newsservices)]=$newsservice;

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

$newservices[] = $newservice;