How create an array from the output of an array printed with print_r?(如何从用 print_r 打印的数组的输出创建一个数组?)
问题描述
我有一个数组:
$a = array('foo' => 'fooMe');
我愿意:
print_r($a);
哪个打印:
Array ( [foo] => printme )
有没有功能,所以在做的时候:
Is there a function, so when doing:
needed_function(' Array ( [foo] => printme )');
我会得到数组 array('foo' => 'fooMe');
回来吗?
I will get the array array('foo' => 'fooMe');
back?
推荐答案
我实际上写了一个函数,将字符串数组"解析为实际数组.显然,它有点 hacky 之类的,但它适用于我的测试用例.这是 http://codepad.org/idlXdij3 上的功能原型的链接.
I actually wrote a function that parses a "stringed array" into an actual array. Obviously, it's somewhat hacky and whatnot, but it works on my testcase. Here's a link to a functioning prototype at http://codepad.org/idlXdij3.
我也将内联代码发布给那些不想点击链接的人:
I'll post the code inline too, for those people that don't feel like clicking on the link:
<?php
/**
* @author ninetwozero
*/
?>
<?php
//The array we begin with
$start_array = array('foo' => 'bar', 'bar' => 'foo', 'foobar' => 'barfoo');
//Convert the array to a string
$array_string = print_r($start_array, true);
//Get the new array
$end_array = text_to_array($array_string);
//Output the array!
print_r($end_array);
function text_to_array($str) {
//Initialize arrays
$keys = array();
$values = array();
$output = array();
//Is it an array?
if( substr($str, 0, 5) == 'Array' ) {
//Let's parse it (hopefully it won't clash)
$array_contents = substr($str, 7, -2);
$array_contents = str_replace(array('[', ']', '=>'), array('#!#', '#?#', ''), $array_contents);
$array_fields = explode("#!#", $array_contents);
//For each array-field, we need to explode on the delimiters I've set and make it look funny.
for($i = 0; $i < count($array_fields); $i++ ) {
//First run is glitched, so let's pass on that one.
if( $i != 0 ) {
$bits = explode('#?#', $array_fields[$i]);
if( $bits[0] != '' ) $output[$bits[0]] = $bits[1];
}
}
//Return the output.
return $output;
} else {
//Duh, not an array.
echo 'The given parameter is not an array.';
return null;
}
}
?>
这篇关于如何从用 print_r 打印的数组的输出创建一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从用 print_r 打印的数组的输出创建一个数组?
基础教程推荐
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01