简体   繁体   English

PHP-将带有前缀的变量放入数组

[英]PHP - Put variables with a prefix into array

Is there any way of putting variables into an array? 有什么方法可以将变量放入数组中? I'm not really sure how else to explain it. 我不太确定该如何解释。

I'm developing a website that works with a game server. 我正在开发一个与游戏服务器兼容的网站。 The game exports a file which contains variables such as: 游戏会导出一个文件,其中包含以下变量:

$RL_PlayerScore_CurrentTrail_14911 = "lasergold";
$RL_PlayerScore_HasTrail_14911_LaserGold = 1;
$RL_PlayerScore_Money_14911 = 2148;

I'd like to convert these into an array like 我想将它们转换成数组

$data = array(
'CurrentTrail_14911' => 'lasergold'
'HasTrail_14911_LaserGold' => '1'
'Money_14911' => '2184'
);

Is there any way I could do this? 有什么办法可以做到吗? Thanks in advance 提前致谢

Include file in scope and then get array of defined vars, excluding globals you don't need. 在范围内包含文件,然后获取已定义的变量数组,排除不需要的全局变量。

include('name-of-your-file.php');

$data = get_defined_vars();
$data = array_diff_key($data, array(
  'GLOBALS' => 1, 
  '_FILES' => 1, 
  '_COOKIE' => 1, 
  '_POST' => 1, 
  '_GET' => 1, 
  '_SERVER' => 1, 
  '_ENV' => 1, 
  'ignore' => 1 )
);

You can return an array with all your declared variables , and loop through them cutting off the desired piece of text. 您可以返回包含所有声明的变量的数组 ,并循环遍历它们以截取所需的文本。 You could do something like this: 您可以执行以下操作:

<?php
//echo your generated file here;
$generatedVars = get_defined_vars();
$convertedArray = array();
foreach($generatedVars as $key=>$var)
{
  $key = str_replace("RL_PlayerScore_","",$key);
  $convertedArray[$key] = $var;
}

If all game variables are going to begin with 'RL_PlayerScore_', you could use something like that : 如果所有游戏变量都将以“ RL_PlayerScore_”开头,则可以使用如下代码:

$vars = [];

foreach($GLOBALS as $var => $value) {
    if(strpos($var, 'RL_PlayerScore_') === 0) {
        $vars[$var] = $value;
    }
}

$vars will be filled by all your variables. $vars将由所有变量填充。

See @Dagon comment also. 另请参阅@Dagon评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM