oli*_*rbj 12 php arrays transformation laravel
所以我有一个嵌套的数组,它模仿表的布局(列和行):
{
"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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
因此,“ 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);
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我的使用方式:
$options = [
'pattern' => '/Trevor/i',
'replacement' => 'Oliver',
];
$engine = new regexTextReplace($options);
$columns = $engine->apply($document->content, 1); //"1" is the specific column.
Run Code Online (Sandbox Code Playgroud)
$columns 返回:
[
{
"row": "My name is Oliver\n"
},
{
"row": "Can you see my?\n"
},
{
"row": "\f"
}
]
Run Code Online (Sandbox Code Playgroud)
这里有两个问题:
1从apply()方法中删除,则会出现以下错误:Array to string conversion
Run Code Online (Sandbox Code Playgroud)
在下面的行中:
return preg_replace($this->pattern, $this->replacement, $table);
Run Code Online (Sandbox Code Playgroud)
谁能指导我正确的方向,以便我可以对任何列或所有列执行解析规则,然后将转换后的数据返回到我的原始数组?
我将重写该apply函数以遍历整个表,如果column未设置参数,或者与当前表的列匹配,则处理每一列:
public function apply(array $table, $column = false): array
{
$out = array();
foreach ($table as $col => $rows) {
if ($column === false || $col == $column) {
$out[$col] = array_map('self::regex_replace', $rows);
}
else {
$out[$col] = $rows;
}
}
return $out;
}
Run Code Online (Sandbox Code Playgroud)