【问题标题】:add values into multidimensional array将值添加到多维数组中
【发布时间】:2015-03-23 20:00:08
【问题描述】:

我有一个遍历项目列表的 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 错误。我做错了什么?

【问题讨论】:

  • $output[$color][] = $person?
  • 还要检查 $color 的值。如果它说非法偏移类型,可能是因为它是一个对象或空值。

标签: php arrays


【解决方案1】:

自从我使用 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);

  }                
}

【讨论】:

  • 是的,它做到了。非常感谢!您需要在 if (!array_key_exists) 语句中添加结束 ) :)
【解决方案2】:

尝试改变:

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

进入:

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

来自array_push上的手册:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2021-12-29
    • 1970-01-01
    • 2014-08-25
    • 2017-12-22
    • 1970-01-01
    • 2014-08-08
    相关资源
    最近更新 更多