【发布时间】: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 的值。如果它说非法偏移类型,可能是因为它是一个对象或空值。