dongpian4954
2017-08-25 22:59
浏览 254
已采纳

动态添加到php const数组?

I know that since php 5.6 you can set a constant as an array, but is it possible to build one dynamically?

This works:

const FIELDS = array("email","firstName");

But I'd like to run a query that populates the constant instead:

while($row = mysqli_fetch_assoc($results)) {
   const FIELDS[] = $row['field'];
}

But that doesn't work. I also tried:

while($row = mysqli_fetch_assoc($results)) {
  $array[] = $row['field'];
}
const FIELDS = $array;

But this also doesn't work. Is there a way to accomplish this? Or does the array have to be hardcoded to be set as a constant?

图片转代码服务由CSDN问答提供 功能建议

我知道自从php 5.6你可以将常量设置为数组,但是可以动态构建一个吗?

这有效:

  const FIELDS = array(“email”,“firstName”); 
   
 
 

但是我想运行一个填充常量的查询:

  while($ row = mysqli_fetch_assoc($ results)){  
 const FIELDS [] = $ row ['field']; 
} 
   
 
 

但这不起作用。 我也尝试过:

  while($ row = mysqli_fetch_assoc($ results)){
 $ array [] = $ row ['field']; 
} 
 nnst  FIELDS = $ array; 
   
 
 

但这也不起作用。 有没有办法实现这个目标? 或者数组是否必须硬编码才能设置为常量?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dsgtew3241 2017-08-27 18:39
    最佳回答

    I fully acknowledge this is an improper use of a constant, and I've since changed it to simply use a variable, HOWEVER -- this is how I did find you could accomplish it:

    while($row = mysqli_fetch_assoc($results)) {
      $array[] = $row['field'];
    }
    DEFINE('FIELDS', serialize($array));
    print_r(unserialize(FIELDS));
    

    Without first serializing the array, I wasn't able to get the DEFINE approach to work (maybe it's different in 7.0?) This requires you to unserialize it before output.

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题