开发者

Storing values in PHP

I am trying to store values in php, like a HashTable with multiple keys. For example I am I w开发者_开发技巧ould want this to return two different values:

$value1=$content['var1']['var2']['var3']['typea'];

$value2=$content['var1']['var2']['var3']['typeb'];

What would be the best way to go about implementing a feature like this?


Instead of building a complicated array, how about you define and use a simple class instead? e.g:

<?php
class beer {
  var $brand;
  var $ounces;
  var $container;
}

$mybeer = new beer();
$mybeer->brand = "Coors";
$mybeer->ounces = 12;
$mybeer->container = "can";

echo $mybeer->brand;
echo $mybeer->ounces;
echo $mybeer->container;
?>


You can set values the same way you get them.

$content['var1']['var2']['var3']['typea'] = $value1;
$content['var1']['var2']['var3']['typeb'] = $value2;


You can take advantage of PHP being a dynamic scripting language by letting it create your desired array structure automatically:

 $content['var1']['var2']['var3']['typea'] = "value1";


One way would be to make a unique key based on the various keys and store it in one big array.

Instead of this,

$value1=$content['var1']['var2']['var3']['typea'];

you'd have something like this...

$contentKey = generateKey("var1", "var2", "var3", "typeA");
$value1 = $content[$contentKey];

where generateKey would do something like hash the various inputs, or concatenate them together with some unique delimiter like a quadruple underscore. This would require fewer array lookups than the other solutions, and (in my opinion) is easier to read.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜