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 :
$vars = [];
foreach($GLOBALS as $var => $value) {
if(strpos($var, 'RL_PlayerScore_') === 0) {
$vars[$var] = $value;
}
}
$vars
will be filled by all your variables.
See @Dagon comment also.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.