使用键推送数组返回错误

时间:2015-03-12 06:55:24

标签: php arrays mysqli

我正在尝试从mysqli查询构建一些子对象。我想创建一个包含许多数组的数组。但是我收到了一些错误

Error: [12-Mar-2015 02:56:23 America/New_York] PHP Warning:  array_push() expects parameter 1 to be array, null given in /home/bud/public_html/cp/function/receivable.php on line 18

这是我的代码:

<?php
require_once('../configuration.php');
$con=new mysqli($hostname,$dbusername,$dbpass,$dbname);
if (mysqli_connect_errno($con)) {
    die('The connection to the database could not be established.');
}
if(isset($_POST['date'])){
  $date=$_POST['date'];
  $receivable= array();
  if($date==="All"){
  $q1="SELECT * FROM orders WHERE order_status='completed' AND due > '0.00' ORDER BY id DESC";
  }else{
  $q1="SELECT * FROM orders WHERE DATE(time) = '$date' AND order_status='completed' AND due > '0.00' ORDER BY id DESC";
  }
  $result=$con->query($q1);
  while($row=$result->fetch_array()){
  //$receivable['orders'][]=array($row);
  array_push($receivable['orders'][], array('id' => $row['id'], 'due' => $row['due'] ));
}
  echo json_encode($receivable);


}  
?>

如何将带密钥的数组插入$receivable['orders'][]; 我想创建更像$receivable['client'][];的数组 并希望将带有键的变量推送到$ receivable ['orders'] [],例如id =&gt;,due =&gt; ,paid =&gt;,

3 个答案:

答案 0 :(得分:2)

您可以在代码中进行一些简单的更改,这样就可以了。

$receivable['orders'][]= array('id' => $row['id'], 'due' => $row['due'] );

这将为数组提供array_push();

答案 1 :(得分:0)

必须以这种方式完成......参数1必须是数组。

// define array
$receivable['orders'] = array();

array_push($receivable['orders'], array('id' => $row['id'], 'due' => $row['due'] ));

答案 2 :(得分:0)

在多维数组中,一个条目是另一个数组,指定该数组的索引为array_push:

  

array_push($ receivable [&#39; orders&#39;],数组(&#39; id&#39; =&gt; $ row [&#39; id&#39;],&#39;到期&# 39; =&gt;   $ row [&#39; due&#39;]));