简体   繁体   中英

How to populate items from the database into a two-dimensional array in PHP

I don't understand how to populate items into a two-dimensional array in PHP. The items are retrieved from the database and get shoved into the two-dimensional array dynamically. I am good with the database part but not the two-dimensional array part. Can someone show me how to accomplish that?

The two-dimensional array that get populated by hand has the following setup. The first array key suppose to contain strings (users: phil, sam, john, peter, jill, etc), the vaulue contains the array of strings (item#: SKU-001, SKU-002, SKU-003, etc), and the value for that array contains integer.

So three things are retrieved from the database and needed to be populated into the two-dimensional array dynamically: users, item# and the integer values.

Here is the two-dimensional array setup and populated by hand:

$products = array(
"phil"   => array("SKU-001" => 1,
                  "SKU-102" => 1,
                  "SKU-203" => 0,
                  "SKU-904" => 1,
                  "SKU-305" => 0,
                  "SKU-006" => 1),

"sam"    => array("SKU-807" => 1,
                  "SKU-608" => 1,
                  "SKU-909" => 0,
                  "SKU-111" => 0,
                  "SKU-512" => 1),

"john"   => array("SKU-013" => 1,
                  "SKU-414" => 0,
                  "SKU-115" => 1),

"peter"  => array("SKU-216" => 1,
                  "SKU-017" => 1),

"jill"   => array("SKU-618" => 1,
                  "SKU-019" => 0,
                  "SKU-120" => 1,
                  "SKU-321" => 1,
                  "SKU-222" => 1,
                  "SKU-123" => 0),

"bruce"  => array("SKU-024" => 1,
                  "SKU-925" => 1,
                  "SKU-028" => 1,
                  "SKU-129" => 1),

"tom"    => array("SKU-330" => 1)
);

How would I get the various keys and values to be populated dynamically into the two-dimensional array in PHP?

Thank you in advance!

You can use foreach

example :-

foreach($products as as $key=>$product){

 echo  $key ;
 echo $product;
}

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