简体   繁体   中英

PHP associative array equivalent in Ruby?

How would one write the following array in Ruby?

 $itemsarray = array();

 $itemsarray["items"]['0']['product_id'] = 1;
 $itemsarray["items"]['0']['brand_id'] = 1;
 $itemsarray["items"]['0']['color_id'] = 1;

 $itemsarray["items"]['1']['product_id'] = 2;
 $itemsarray["items"]['1']['brand_id'] = 3;
 $itemsarray["items"]['1']['color_id'] = 5;

It's very easy. Here is what you will need:

itemsarray = { 'items' => [ { 'product_id' => 1, 'brand_id' => 1, 'color_id' => 1 } ] }

Now a little bit of explanation...

In Ruby to represent an associative array we use Hashes . Ex.: { 'a' => 1, 'b' => 2 } == array('a' => 1, 'b' => 2) .

So at the top level you have a hash containing the key items and it's value is an array of all the items. The first item is a hash again, having the product options as keys with their corresponding values.

What is a bit better way to write this is to use symbols instead of strings for the keys, as this will introduce a slight memory optimisation. Here is an example:

itemsarray = { :items => [ { :product_id => 1, :brand_id => 1, :color_id => 1 } ] }

There is also a shorthand syntax where :abc => 1 is equivalent to: abc: 1 , so the above line would look like:

itemsarray = { items: [ { product_id: 1, brand_id: 1, color_id: 1 } ] }

UPDATE

With multiple items, here is how it would look like:

itemsarray = { items: [
                          { product_id: 1, brand_id: 1, color_id: 1 },
                          { product_id: 2, brand_id: 3, color_id: 5 }
                      ]}

Or a dynamic approach:

itemsarray[:items].push( { product_id: 2, brand_id: 3, color_id: 5 } )
itemsarray={ items:[{product_id:1, brand_id:1, color_id:1} ]}

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