前段时间我通过一些 API 获取了大量数据,然后通过简单的 var_dump 或 print_r 将其保存到一个平面文件中。现在我正在处理数据,每一行看起来像:
" 'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y', 'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name' => 'MNOP', 'email' => 'abc@example.com', 'city' => 'London', 'street_address' => 'Sample', 'first_name' => 'Sparsh',"
现在我需要将这些数据恢复为数组格式。有什么办法可以做到吗?
最佳答案
首先用 explode()
分解字符串怎么样?函数,使用 ', '
作为分隔符:
$str = "'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y', 'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name' => 'MNOP', 'email' => 'abc@example.com', 'city' => 'London', 'street_address' => 'Sample', 'first_name' => 'Sparsh',";
$items = explode(', ', $str);
var_dump($items);
这会让你得到一个看起来像这样的数组:
array
0 => string ''middle_initial' => ''' (length=22)
1 => string ''sid' => '1419843'' (length=18)
2 => string ''fixed' => 'Y'' (length=14)
3 => string ''cart_weight' => '0'' (length=20)
...
然后,遍历该列表,匹配 =>
每一侧的每个项目,并使用 =>
的第一侧作为结果数据的键,第二个作为值:
$result = array();
foreach ($items as $item) {
if (preg_match("/'(.*?)' => '(.*?)'/", $item, $matches)) {
$result[ $matches[1] ] = $matches[2];
}
}
var_dump($result);
哪个会让你:
array
'middle_initial' => string '' (length=0)
'sid' => string '1419843' (length=7)
'fixed' => string 'Y' (length=1)
'cart_weight' => string '0' (length=1)
...
但是,严重的是,您不应该以这种糟糕的格式存储数据:print_r()
用于显示数据,用于调试目的——而不是存储它并稍后重新加载它!
如果要将数据存储到文本文件,请使用 serialize()
或 json_encode()
, 都可以使用 unserialize()
恢复或 json_decode()
,分别。
关于php - 将字符串转换为数组 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6802389/