PHP函数解析多维数组?

时间:2013-04-18 19:54:16

标签: php mysql arrays multidimensional-array pdo

我运行了一个查询fetchAll()

$query = "SELECT uid, kill_count FROM users WHERE curmid=:mid AND status='1'";
...
$row = $stmt->fetchAll();

返回此数组:

Array ( 
 [0] => Array ( [uid] => 105 [fcount] => 1 ) 
 [1] => Array ( [uid] => 106 [fcount] => 2 ) 
 [2] => Array ( [uid] => 107 [fcount] => 0 ) 
 [3] => Array ( [uid] => 108 [fcount] => 1 ) 
 [4] => Array ( [uid] => 109 [fcount] => 1 ) 
)  

我有一个循环,我想通过它基本上运行它:

$problist = array();
foreach ($row as $key => $value) {
    if ($value == 0) {
        array_push($problist, $key, $key, $key, $key, $key);
    } elseif ($value == 1) {
        array_push($problist, $key, $key, $key);
    } elseif ($value >= 2) {
        $problist[] = $key;
    }
}

当然,该循环不起作用,因为它没有引用数组中的正确值。在这个假设中,我正在寻找的输出是:$problist =

array(15) { 
[0]=> string(3) "105" 
[1]=> string(3) "105" 
[2]=> string(3) "105" 
[3]=> string(3) "106" 
[4]=> string(3) "107" 
[5]=> string(3) "107" 
[6]=> string(3) "107" 
[7]=> string(3) "107" 
[8]=> string(3) "107" 
[9]=> string(3) "108" 
[10]=> string(3) "108" 
[11]=> string(3) "108"
[12]=> string(3) "109" 
[13]=> string(3) "109" 
[14]=> string(3) "109" 
}  

我已阅读并修改,然后阅读并修补无法弄清楚使用哪些PHP函数来实现此功能。我尝试过end()reset()array_shift()和其他人。在我的无知中,我当然没有正确使用它们。谢谢你的帮助。

[也许甚至有更好的方法来格式化我的查询?]

2 个答案:

答案 0 :(得分:3)

$problist = array();
foreach ($row as $value) {
    if ($value['fcount'] == 0) {
        array_push($problist, $value['uid'], $value['uid'], $value['uid'], $value['uid'], $value['uid']);
    } elseif ($value['fcount'] == 1) {
        array_push($problist, $value['uid'], $value['uid'], $value['uid']);
    } elseif ($value['fcount'] >= 2) {
        $problist[] = $value['uid'];
    }
}

答案 1 :(得分:1)

您正在循环遍历整个结果集,因此$value是一个类似于:

的数组
$value = array(
    'uid' => 105,
    'fcount' => 1
);

因此,在您的代码中,您应使用$value['uid']代替$key$value['fcount']代替$value