将关联和索引数组转换为关联数组

时间:2017-06-23 11:32:19

标签: php

   Array ( [0] => Array ( [pkg_id] => 00004 [0] => 00004 [food_cat] => 
    starter  [1] => starter [max_price] => 2 [2] => 2 [max_item] => 2 [3] => 
    2 [sub_text] => select any 1 [4] => select any 1 [display_seq] => 1 [5] 
    => 1 ) [1] => Array ( [pkg_id] => 00004 [0] => 00004 [food_cat] => main 
    course [1] => main course [max_price] => 6 [2] => 6 [max_item] => 4 [3] 
    => 4 [sub_text] => select any 3 [4] => select any 3 [display_seq] => 2 
    [5] => 2 ) [2] => Array ( [pkg_id] => 00004 [0] => 00004 [food_cat] => 
    desert [1] => desert [max_price] => 3 [2] => 3 [max_item] => 2 [3] => 2 
    [sub_text] => select any 1 [4] => select any 1 [display_seq] => 3 [5] => 
    3 ) )

这是我在数据库中运行select查询时形成的数组。查询结果形成一个数组,它是关联和索引数组的组合。您可以看到重复的值。 我想有没有任何方法将这个数组转换为只有关联数组?

2 个答案:

答案 0 :(得分:1)

使用PDO::FETCH_ASSOC: fetch_style

喜欢

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
  

PDO :: FETCH_ASSOC:返回由返回的列名索引的数组   在结果集中

检查所有PDOStatement :: fetch here

答案 1 :(得分:0)

您可以使用$stmt->->fetchAll(PDO::FETCH_ASSOC);来获取关联数组。使用以下代码:

$conn=newPDO("mysql:host=$servername;dbname=$dbname",$userna‌​me,$password);
$conn>setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION)‌​; 
$stmt=$conn->prepare("select * from food_package_details where pkg_id=:pkgid");
$stmt->bindparam(":pkgid",$pkg);
$stmt->execute();
$stmt->->fetchAll(PDO::FETCH_ASSOC);