【问题标题】:How to get the value of a constant and save it to the database如何获取常量的值并将其保存到数据库中
【发布时间】:2021-03-15 09:28:29
【问题描述】:

我有一个像这样的常量类

Class MyConstants
{
const TEST = "asd";
const TEST123 = "foo";
const TEST333 = "fooBar";
const TEST321 = "bar";
}

在我的控制器中,我获取所有常量并随机选择 3,问题是我只从常量中获取密钥,但我需要值

$allConstants = $this->getAllConstants();
$foo = array_rand($allConstants, 3);

dd($foo)

 array:3 [
  0 => "TEST321"
  1 => "TES"
  2 => "TEST123"
 ]

我怎样才能得到常量的值,例如 foobar ?

然后我还需要将它们保存到数据库中。我应该循环它们吗?

$fooBarEntity->setData($foo);

感谢您的帮助。

【问题讨论】:

标签: php arrays constants


【解决方案1】:

array_flip 将所有键与它们在数组中的关联值交换。 试试这个:

Class MyConstants
{
    const TEST = "asd";
    const TEST123 = "foo";
    const TEST333 = "fooBar";
    const TEST321 = "bar";
}

$reflection = new ReflectionClass(MyConstants::class);
$values = $reflection->getConstants();
$data = array_rand(array_flip($values), 3);
foreach($data as $item) {
    #$fooBarEntity->setData($item);
}
print_r($data);

【讨论】:

  • 记住在使用array_flip()时要小心,因为如果数组中多次出现相同的值,除了最后一个之外的每个对应的键都会丢失。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-12
  • 2018-11-11
  • 1970-01-01
  • 2016-12-30
  • 2016-11-15
  • 2011-09-25
相关资源
最近更新 更多