【发布时间】:2019-10-03 11:02:33
【问题描述】:
所以我有一个嵌套数组,它模仿表格布局(列和行):
{
"1": [
{
"row": "My name is Trevor\n"
},
{
"row": "Can you see me?\n"
},
{
"row": "\f"
}
],
"2": [
{
"row": Hey there! Some other text.\n"
},
{
"row": "What is up?\n"
},
{
"row": "\f"
}
],
"3": [
{
"row": "Some text on the third column. First row."
},
{
"row": "\f"
}
]
}
所以“1”、“2”、“3”是列,然后在每列下,可以有任意数量的行。
现在我正在尝试这样做,这样我的用户就可以对任何一个执行各种解析规则:
- 所有列和所有行。
- 特定列和所有行。
每当一个列/行被解析后,它应该返回到“原始数组”。
为此,我创建了一个类,它将应用我指定的不同解析规则。获取解析规则工作正常。我目前停留在实际的文本转换/解析方面。
假设我有一个名为“regexTextReplace”的解析规则,如下所示:
class regexTextReplace
{
private $pattern;
private $replacement;
public function __construct(array $arguments)
{
$this->pattern = $arguments['pattern'];
$this->replacement = $arguments['replacement'];
}
public function apply(array $table, $column = false): array
{
$table = $column ? $table[$column] : $table;
return array_map('self::regex_replace', $table);
}
public function regex_replace(array $table)
{
return preg_replace($this->pattern, $this->replacement, $table);
}
}
这就是我的使用方式:
$options = [
'pattern' => '/Trevor/i',
'replacement' => 'Oliver',
];
$engine = new regexTextReplace($options);
$columns = $engine->apply($document->content, 1); //"1" is the specific column.
$columns 返回:
[
{
"row": "My name is Oliver\n"
},
{
"row": "Can you see my?\n"
},
{
"row": "\f"
}
]
这里有两个问题:
- 它成功应用了解析规则(Trever 被替换为 Oliver)。但它只返回第一列,但我希望对整个原始数组进行转换。
- 如果我从
apply()方法中删除1,则会出现以下错误:
Array to string conversion
在下面一行:
return preg_replace($this->pattern, $this->replacement, $table);
谁能指导我正确的方向,这样我就可以对任何列或所有列执行我的解析规则,并将转换后的数据返回到我的原始数组?
【问题讨论】:
-
因为这看起来很复杂:您是否尝试过将 TDD 应用于此?就像开始为最简单的案例编写测试,然后继续下一个更困难的案例?这将帮助你保持这个类的可维护性
-
在此处查看您的条件:当
column参数为假值时,$table = $column ? $table[$column] : $table;表将作为数组出现,因此它抱怨Array to string conversion。我宁愿让table的值保持一致,也就是一个数组,然后每次apply()接到一个调用就简单的循环一遍。
标签: php arrays laravel transformation