将值添加到多维数组中


add values into multidimensional array

我有一个foreach循环,它遍历项目列表。对于这些项目中的每一个,我都有一个while循环,用于从数据库中获取数据。

$output = array();
//$reference is a multidimensional array has been passed to this page
where the element `color` contains the color I want.
foreach ($reference as $c) {
  $color = $c['color'];
$query = "SELECT DISTINCT name FROM $table where colorPreference = $color";
$exquery = mysqli_query($con, $customerQuery);
while ($row = mysqli_fetch_array($exquery)) {
$person = $row['person'];
array_push($output[$color], $person);
  }                
}

所以这个循环通过,第一次搜索"红色",在假表中找到5个喜欢红色的人。接下来是"蓝色",在其中找到1个人,然后是"绿色",在那里找到3个人。

如果我查看单个结果,我的第一个数组有"红、蓝、绿",第二个数组有这些名称列表。。。。我只是不知道如何将它们一起添加到数组中。

我正在尝试构建一个这样的数组:

Array
(
  [Red] => Array
      (
          [0] => John
          [1] => Sally
          [2] => Bob
          ...
      )
  [Blue] => Array
      (
          [0] => Luke
      )
  [Green] => Array
      (
          ..etc...       
      )

不过,我没有正确使用array_push——我收到了一个Warning: Illegal offset type错误。我做错了什么?

我已经有一段时间没有使用PHP了,但我认为您需要初始化要推入的每个"颜色"数组。所以…

$output = array();
//$reference is a multidimentional array has been passed to this page
where the element `color` contains the color I want.
foreach ($reference as $c) {
  $color = $c['color'];
  $query = "SELECT DISTINCT name FROM $table where colorPreference = $color";
  $exquery = mysqli_query($con, $customerQuery);
  while ($row = mysqli_fetch_array($exquery)) {
    $person = $row['person'];
    if (!array_key_exists($color, $output)) {
      $output[$color] = array();
    }
    array_push($output[$color], $person);
  }                
}

尝试更改:

array_push($output[$color], $person);

进入:

$output[$color][] = $person;

来自array_push:上的手册

注意:如果使用array_push()向数组中添加一个元素,那么最好使用$array[]=,因为这样就没有调用函数的开销。

注意:如果第一个参数不是数组,array_push()将引发警告。这与创建新数组的$var[]行为不同。