PHP解析sql结果集
问题描述:
我想解析一个SQL结果集,我遇到了多个问题。PHP解析sql结果集
foreach ($rows as $key => $row) {
die(print(gettype($row))); // DIE 1
if (is_array($row)) {
foreach ((array)$row as $k => $r) {
die(print_r($r)); // DIE 2
if (!in_array($r['proposal'], $proposals)) {
array_push($proposals, $r['proposal']);
}
if (!in_array($r['question'], $scorequestions) && $r['type'] == 'score') {
array_push($scorequestions, $r['question']);
}
if (!in_array($r['question'], $recommendquestions) && $r['type'] == 'recommend') {
array_push($recommendquestions, $r['question']);
}
}
}
}
我$行是:(http://i.imgur.com/YUpZvBx.png)
+----------+--------+----------+-----------+----------+---------+-----------+-------------+------+
| question | title | campaign | type | proposal | avg | recommend | conditional | cnt |
+----------+--------+----------+-----------+----------+---------+-----------+-------------+------+
| 101 | Title1 | 104 | score | 38 | 6.6667 | 0 | 0 | 3 |
| 101 | Title2 | 104 | score | 39 | 9.6667 | 0 | 0 | 3 |
| 101 | Title3 | 104 | score | 40 | 8.0000 | 0 | 0 | 2 |
| 101 | Title4 | 104 | score | 41 | 3.0000 | 0 | 1 | 2 |
| 101 | Title5 | 104 | score | 42 | 9.0000 | 0 | 0 | 1 |
| 101 | Title6 | 104 | score | 43 | 9.0000 | 0 | 0 | 1 |
| 101 | Title7 | 104 | score | 44 | 7.6667 | 0 | 0 | 3 |
$行是一个SQL结果集。 DIE 1 print告诉我$ row是一个数组,但是is_array()函数认为它不是数组。
如果我跳过,如果循环(其注释掉),并运行内部foreach循环,模具2给我:
Array ([question] => 105 [campaign] => 104 [type] => recommend [proposal] => 42 [avg] => -1.0000 [recommend] => 1 [conditional] => 1 [cnt] => 1 [title] => Title5 [amount] => 300 [theme] => offline) 1
但后来我得到$ R [“建议”的非法串偏移误差]。不知道我哪里错了。在发布之前,我已阅读了多个SO线程。
答
您直接在$ rows上迭代,而$ rows是具有包含实际数据的$ rows成员的对象。所以你应该迭代外循环中的$ rows->行。
嗨@u_mulder请多一点解释?我该如何解决和在哪里? – Chocolava 2015-04-05 19:08:02
如果我这样写: foreach($ row = $ k => $ r) 然后我得到:为foreach提供的无效参数() – Chocolava 2015-04-05 19:10:06
如何获取$ rows变量?你可以发布一个样本吗? – Cristik 2015-04-05 19:10:27