从嵌套的foreach循环中获取重复的结果

时间:2014-08-28 14:48:08

标签: php html mysql loops pdo

我正在尝试从Google Line Chart API:

的mysql获取以下输出
[["product","diameter","width"],["Product 1","2","4"],["Product 2","4","8"]]

我已经设置了几个输入复选框,通过$_POST["info"]向数据库发送字段名称(例如宽度,直径),并从这些字段中检索值。这是从mysql生成数据的部分:

$result = $users->fetchAll();
$comma = "";
$data="";
$data[0] = array_merge(array(product),$info);   
$i = 1;
foreach ($result as $r)
{
    foreach($_POST["info"] as $p)
    {    
        $d .= $comma.$r[$p];     // trying to get "$r["width"],$r["diameter"]"            
    }
    $comma = ",";
    $data[$i] = array($r["name"], $d);
    $i++;
}   
echo json_encode($data);

我想要的输出应该是这样的:

[["product","diameter","width"],["Product 1","2","4"],["Product 2","4","8"]]

但是该代码正在生成像这样的重复结果

[["product","diameter","width"],["Product 1","24"],["Product 2","24,4,8"]]

我想我不应该使用嵌套的foreach来遍历$_POST。谁能告诉我如何解决这个问题?

完整的PHP代码:

$info = $_POST["info"]; // It contains an array with values like width,diameter,thickness etc...
$comma = "";
foreach($info as $in)
{ 
    $field .= "".$comma."b.".$in."";
    $comma = ",";
}

$sql = "
        SELECT {$field},a.user_id,a.name
        FROM `product_detail` a INNER JOIN
        `attr` b ON a.model = b.model 
        WHERE a.user_id = ?
        GROUP BY a.model
       ";
$users = $dbh->prepare($sql);
$users->bindValue(1, $_SESSION["user_id"]);  
$users->execute();
$result = $users->fetchAll();
$comma = "";
$data="";
$i = 1;
$data[0] = array_merge(array(product),$info);       
foreach ($result as $r)
{
    foreach($_POST["info"] as $p)
    {    
        $d .= $comma.$r[$p];                
    }
    $comma = ",";
    $data[$i] = array($r["name"], $d);
    $i++;
}   
echo json_encode($data);

$ _ POST [“info”]内容:

Array
(
    [0] => diameter
    [1] => width
)

3 个答案:

答案 0 :(得分:1)

尝试这样:

$result = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);   
$i = 1;
foreach ($result as $r)
{
    $d[]=$r["name"];
    foreach($_POST["info"] as $p)
    {    
        $d[]= $r[$p];
    }
    $data[$i] = $d;
    $d=array(); //set $d to empty not to get duplicate results
    $i++;
}   
echo json_encode($data);

答案 1 :(得分:0)

您正在寻找的最终结果是有效的JSON。你不应该尝试手动生成它。

相反,你应该在php中创建一个数组数组,并使用json_encode($array)来获得你想要的结果。

另请注意,通过直接在查询中注入POST变量,您很容易受到SQL注入攻击。接受字段时,应根据允许值的白名单进行检查。

答案 2 :(得分:0)

尝试以下解决方案:

$result = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);   
$i = 1;
foreach ($result as $r)
{
    $d = array();
    foreach($_POST["info"] as $p)
    {    
        $d[] = $r[$p];     // trying to get "$r["width"],$r["diameter"]"            
    }
    $data[$i] = array($r["name"]) +$d;
    $i++;
}   
echo json_encode($data);