在 PHP 中存储值

发布于 2024-09-29 19:42:48 字数 205 浏览 3 评论 0原文

我试图在 php 中存储值,就像具有多个键的哈希表一样。例如,我希望它返回两个不同的值:

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

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

实现这样的功能的最佳方法是什么?

I am trying to store values in php, like a HashTable with multiple keys. For example I am I would 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

笑脸一如从前 2024-10-06 19:42:48

与其构建复杂的数组,不如定义并使用一个简单的类怎么样?例如:

<?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;
?>

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;
?>
吻风 2024-10-06 19:42:48

您可以按照获取值的方式设置值。

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

You can set values the same way you get them.

$content['var1']['var2']['var3']['typea'] = $value1;
$content['var1']['var2']['var3']['typeb'] = $value2;
千年*琉璃梦 2024-10-06 19:42:48

您可以利用 PHP 作为动态脚本语言的优势,让它自动创建您想要的数组结构:

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

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";
蓬勃野心 2024-10-06 19:42:48

一种方法是根据各种密钥创建一个唯一的密钥并将其存储在一个大数组中。

相反,

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

你会得到类似这样的东西...

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

其中 generateKey 会执行诸如散列各种输入之类的操作,或者将它们与一些唯一的分隔符(例如四重下划线)连接在一起。与其他解决方案相比,这需要更少的数组查找,并且(在我看来)更易于阅读。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文