简体   繁体   中英

how to print 2d array in php from database values

I need to print an 2d array like this from values fetched from database having table 'product' whose structure is like this

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

I wan't output like below using 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)

);

i have tried this i am using php/mysql I wan't to get table data into a 2d array and i have tried like this

$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);

but it is not working

So if you want product_name field be a key and rating field be a value:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM