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

时间:2013-11-23 15:03:37

标签: php sql multidimensional-array

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

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

               }

    }

4 个答案:

答案 0 :(得分:1)

试试这个:

array_push ($newservices, $newservice);

而不是:

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

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

答案 1 :(得分:0)

多数民众赞成因为$newservices[count($newservices)]不是数组

在此处阅读文档array_push

只是为了解决错误,你可以做到这一点

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

答案 2 :(得分:0)

尝试替换此代码

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

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

答案 3 :(得分:0)

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

$newservices[] = $newservice;