add values into multidimentional array

I have a foreach loop that goes through a list of items. For each of these items, I have a while loop that grabs data out of a database.

$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'];
array_push($output[$color], $person);

  }                
}

So this loops through, the first time searching 'red', and finding 5 people in the fake table who like red. Next, 'blue', where it finds 1 person, and then 'green' where it finds 3.

If I look at the individual results, my first array has "red, blue, green" and my second array has these lists of names.... I just don't know how to add them into an array together.

I'm trying to build an array like this:

Array
(
  [Red] => Array
      (
          [0] => John
          [1] => Sally
          [2] => Bob
          ...
      )

  [Blue] => Array
      (
          [0] => Luke
      )
  [Green] => Array
      (
          ..etc...       
      )

I'm not using array_push correctly though - I'm getting an Warning: Illegal offset type error. What am I doing wrong?


It's been a while since I've worked with PHP, but I think you need to initialize each "color" array that you're going to push into. So...

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

  }                
}

Try changing:

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

Into:

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

From the manual on array_push:

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.

链接地址: http://www.djcxy.com/p/47812.html

上一篇: 使用Symfony Twig从数据库中分辨Blob图像

下一篇: 将值添加到多维数组中