使用PHP提取数组键和值

时间:2015-03-15 11:29:06

标签: php mysql arrays multidimensional-array pdo

早安, 我有这个阵列:

Array (
    [0] => Array ( [ID] => 11 [Nome] => Ponte 1)
    [1] => Array ( [ID] => 12 [Nome] => Ponte 2 ) 
    [2] => Array ( [ID] => 13 [Nome] => Ponte 3 ) 
    [3] => Array ( [ID] => 14 [Nome] => Ponte 4 ) 
    [4] => Array ( [ID] => 15 [Nome] => Ponte 5 ) 
    [5] => Array ( [ID] => 16 [Nome] => Ponte 6 ) 
    [6] => Array ( [ID] => 17 [Nome] => Ponte 7 ) 
    [7] => Array ( [ID] => 18 [Nome] => Ponte 8 ) 
    [8] => Array ( [ID] => 19 [Nome] => Ponte 9 ) 
    [9] => Array ( [ID] => 20 [Nome] => Ponte 10 ) 
    [10] => Array ( [ID] => 21 [Nome] => Ponte 11 ) 
    [11] => Array ( [ID] => 22 [Nome] => Ponte 12 ) 
    [12] => Array ( [ID] => 23 [Nome] => Ponte 13 ) 
    [13] => Array ( [ID] => 24 [Nome] => Ponte 14 ) 
    [14] => Array ( [ID] => 25 [Nome] => Ponte 15 ) 
    [15] => Array ( [ID] => 26 [Nome] => Ponte 16 ) 
    [16] => Array ( [ID] => 27 [Nome] => Ponte 17 ) 
    [17] => Array ( [ID] => 28 [Nome] => Ponte 18 ) 
    [18] => Array ( [ID] => 29 [Nome] => Ponte 19 ) 
    [19] => Array ( [ID] => 30 [Nome] => Ponte 20 ) 
    [20] => Array ( [ID] => 31 [Nome] => Ponte 21 ) 
    [21] => Array ( [ID] => 32 [Nome] => Ponte 22 ) 
    [22] => Array ( [ID] => 33 [Nome] => Ponte 23 ) 
    [23] => Array ( [ID] => 34 [Nome] => Ponte 24 )
)

我必须只提取数组中的对象:

... etc ...
[ID] => 34 [Nome] => Ponte 24

我怎么能这样做,假设我在这个用MySql创建该数组的类中使用PHP PDO:

$stmt = $this->conn->getConnection()->prepare($query);
foreach($bindParam as $key => &$val){
    $stmt->bindParam($key,$val);
}
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
return ($row);

使用此查询调用:

$query = $query->selectAll("SELECT Name,ID FROM Table WHERE field = :field",array(":field" => 10));

这就是我所做的:

foreach ( $query as $key => $val) {
    echo $key."--".$val."<br/>";
}

但似乎没有用,有办法吗? 谢谢你。

4 个答案:

答案 0 :(得分:0)

试试这个:

foreach ($query as $q) {
    foreach ($q as $key => $val) {
        echo $key."--".$val."<br/>";
    }
}

答案 1 :(得分:0)

你需要迭代$val,因为它也是一个数组..

foreach ( $query as $key => $val) {
    echo $key."--".$val."<br/>";
    foreach($val as $key1 => $val1){
        echo $key1."--".$val1."<br/>";
    }
}

HTH!

答案 2 :(得分:0)

如果您只想回复每个ID和名称:

foreach ( $query as $val) {
echo $val["ID"];
echo  "--";    
echo $val["nome"];
echo "<br/>";
}

答案 3 :(得分:0)

这是正确的方法:

foreach ( $query as $val) { echo $val['ID']."--".$val['Nome']."<br/>"; }

谢谢Mark。