问题描述
这是$preparedstring
的一部分:
我正在尝试将HTML表转换为多维数组.我已将表转换为长字符串,每个单元格均以逗号分隔,每行均以分号分隔.
I am trying to convert a HTML table to a multidimensional array. I have converted the table into a long string, each cell being delimited with a comma and each row being delimited with a semicolon.
我不确定如何从此字符串构建多维数组.到目前为止,这是我尝试过的:
I am not exactly sure how to build the multidimensional array from this string. This is what I have tried so far:
<?php
$outerARR = explode(";", $preparedstring);
$arr = array
(
foreach ($outerARR as $arrvalue) {
$innerarr = explode(",", $arrvalue);
$innerarr[0]=>array
(
$innerarr[];
)
}
);
?>
这使我在
左括号.
推荐答案
您解决问题的方法非常可悲,尽管您的问题有很多解决方案,但我会使用类似以下的内容.
Your approach to solving the problem is sadly very wrong, though there are many solutions to your problem, I would use something like the below.
代码如何工作?
首先,我们使用爆炸将字符串分成较小的块,;
是我们的分隔符.
First we use explode to split our string up in smaller chunks, ;
is our delimiter.
我们将此新创建的数组传递给 array_map 第二个参数.
We pass this newly created array to array_map as it's second parameter.
array_map 具有两个参数,第一个是将为第二个参数的每个成员(应为数组)调用的函数.
array_map takes two parameters, the first one is a function that will be called for every member of the second paramater (which should be an array).
在我们对 array_map 的回调中,我们使用分解再次拆分出值,现在以,
作为分隔符.
Inside our callback to array_map we use explode to once again split out the values, now with ,
as our delimiter.
$data = "1,2,3;4,5,6;7,8,9";
$ret = array_map (
function ($_) {return explode (',', $_);},
explode (';', $data)
);
print_r ($ret);
输出
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[2] => Array
(
[0] => 7
[1] => 8
[2] => 9
)
)
它不起作用,为什么?
可能是因为您使用的是5.3之前的PHP版本,如果可以,则可以改用以下代码段:
Probably because you are using a version of PHP prior to 5.3, if so you can use this snippet instead:
function explode_by_comma ($_) {
return explode (',', $_);
}
$ret = array_map ('explode_by_comma', explode (';', $data));
这篇关于从字符串php构建多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!