将 PHP 数组字符串转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/684553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert PHP array string into an array
提问by Peter Craig
I have an array:
我有一个数组:
$myArray = array('key1'=>'value1', 'key2'=>'value2');
I save it as a variable:
我将它保存为一个变量:
$fileContents = var_dump($myArray);
How can convert the variable back to use as a regular array?
如何将变量转换回用作常规数组?
echo $fileContents[0]; //output: value1
echo $fileContents[1]; //output: value2
回答by Paolo Bergantino
I think you might want to look into serializeand unserialize.
我想你可能想研究serialize和unserialize。
$myArray = array('key1'=>'value1', 'key2'=>'value2');
$serialized = serialize($myArray);
$myNewArray = unserialize($serialized);
print_r($myNewArray); // Array ( [key1] => value1 [key2] => value2 )
回答by Binny V A
serialize might be the right answer - but I prefer using JSON - human editing of the data will be possible that way...
序列化可能是正确的答案 - 但我更喜欢使用 JSON - 这样就可以人工编辑数据......
$myArray = array('key1'=>'value1', 'key2'=>'value2');
$serialized = json_encode($myArray);
$myNewArray = json_decode($serialized, true);
print_r($myNewArray); // Array ( [key1] => value1 [key2] => value2 )
回答by Jake McGraw
Try using var_exportto generate valid PHP syntax, write that to a file and then 'include' the file:
尝试使用var_export生成有效的 PHP 语法,将其写入文件,然后“包含”该文件:
$myArray = array('key1'=>'value1', 'key2'=>'value2');
$fileContents = '<?php $myArray = '.var_export($myArray, true).'; ?>';
// ... after writing $fileContents to 'myFile.php'
include 'myFile.php';
echo $myArray['key1']; // Output: value1
回答by KRavEN
How about eval? You should also use var_export with the return variable as true instead of var_dump.
评价怎么样?您还应该使用 var_export 并将返回变量设为 true 而不是 var_dump。
$myArray = array('key1'=>'value1', 'key2'=>'value2');
$fileContents = var_export($myArray, true);
eval("$fileContentsArr = $fileContents;");
echo $fileContentsArr['key1']; //output: value1
echo $fileContentsArr['key2']; //output: value2
回答by Nady Shalaby
$array = ['10', "[1,2,3]", "[1,['4','5','6'],3]"];
function flat($array, &$return) {
if (is_array($array)) {
array_walk_recursive($array, function($a) use (&$return) { flat($a, $return); });
} else if (is_string($array) && stripos($array, '[') !== false) {
$array = explode(',', trim($array, "[]"));
flat($array, $return);
} else {
$return[] = $array;
}
}
$return = array();
flat($array, $return);
print_r($return);
OUTPUT
输出
Array ( [0] => 10 [1] => 1 [2] => 2 [3] => 3 [4] => 1 [5] => '4' [6] => '5' [7] => '6'] [8] => 3 )
回答by Rain
Disclaimer
免责声明
I wrote this function (out of fun:)and because I'm lazy AF I wanted a short way to convert an array inside a string to a valid PHP array. I'm not sure if this code is 100% safe to usein production as execand it's sisters always scare the crap out of me.
我写了这个函数(出于乐趣:),因为我很懒惰,所以我想要一种将字符串中的数组转换为有效 PHP 数组的简短方法。我不确定这段代码在生产中是否 100% 安全,因为exec它的姐妹们总是吓唬我。
$myArray = 'array("key1"=>"value1", "key2"=>"value2")';
function str_array_to_php(string $str_array) {
// No new line characters and no single quotes are allowed
$valid_str = str_replace(['\n', '\''], ['', '"'], $str_array);
exec("php -r '
if (is_array($valid_str)) {
function stap($arr = $valid_str) {
foreach($arr as $v) {
if(is_array($v)){
stap($v);
}
else {
echo $v,PHP_EOL;
}
}
}
stap();
}'2>&1", $out);
return $out;
}
print_r(str_array_to_php($myArray));
Output:
输出:
Array ( [0] => value1 [1] => value2 )
As you can see, it will convert $myArrayinto a valid PHP array, and then indexes it numerically and if it is multidimensional it will convert it into single one.
如您所见,它将转换$myArray为有效的 PHP 数组,然后对其进行数字索引,如果它是多维的,则将其转换为单个数组。
BE CAREFUL:
1- never pass the array in double quotesas this will allow null byte characters (\0) to be evaluated.
当心:
1-永远不要在双引号中传递数组,因为这将允许评估空字节字符 (\0)。
For example:
例如:
$myArray = "array(\"key1\"=>\"value\n##代码## ggg\", \"key2\"=>\"value2\")"
//Output: Warning: exec(): NULL byte detected. Possible attack
2- This function wont work if
execis disabled (Mostly will be )3- This function wont work if
phpcommand is not set
2- 如果
exec被禁用,此功能将无法工作(主要是)3- 如果
php未设置命令,此功能将不起作用
One last thing, if you find any error or flaws please let me know in the comments so i can fix it and learn.
最后一件事,如果您发现任何错误或缺陷,请在评论中告诉我,以便我可以修复它并学习。
Hope this helps.
希望这可以帮助。

