如何从数据库值

时间:2015-10-07 16:39:15

标签: php arrays

我需要从具有表&产品'的数据库中提取的值打印这样的2d数组。其结构如下

name   product_name   rating 
rahul  fifa 15         3
rahul  gta 5           4
bidur  GOD OF WAR     3.5
bidur  gta 5          4

我不会使用php / mysql

输出如下
$books = array(

"rahul" => array("fifa 15" => 3,"gta 5" => 4),

"bidur" => array("GOD OF WAR" => 3.5,"gta 5" => 4),

"sushil" => array("HEAVY RAIN" => 4),

"vivek" => array("FIFA 15" => 3,"gta 5" => 4),

"anup" => array("Read Dead Redemption" => 4.5),

"nikhil" => array("FAR CRY 4" => 4.5,"HEAVY RAIN" => 3),

"akhi" => array("WWE RAW" => 3.5)

);

我试过这个 我正在使用php / mysql我不想把表数据变成二维数组而且我试过这样的

$books=array();

$sql="select distinct(email) from product_order";
$result=mysqli_query($con,$sql) or die($con->error);

while($row=mysqli_fetch_array($result))
{

    $email=$row['email'];
    $query="select product_name,rating from product_order where email='$email'";
    $result=mysqli_query($con,$query) or die($con->error);


    while($r=mysqli_fetch_array($result))
    {
        $books["$email"][]=$r["product_name"];
        $books["$email"][]=$r["rating"];
    }

}


if($result) echo 'success';
else 'failure';

print_r($books);

但它不起作用

1 个答案:

答案 0 :(得分:0)

因此,如果您希望product_name字段为关键字,rating字段为值:

while($r=mysqli_fetch_array($result))
{
    $books["$email"][$r["product_name"]]=$r["rating"];
}