gpt4 book ai didi

PHP - 对嵌套数组执行解析规则

转载 作者:行者123 更新时间:2023-12-03 00:57:17 24 4
gpt4 key购买 nike

所以我有一个嵌套数组,它模仿表格布局(列和行):

{
"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”是列,然后在每列下可以有任意数量的行。

现在我正在尝试这样做,以便我的用户可以在以下任一方面执行各种解析规则:

  1. 所有列和所有行。
  2. 特定列和所有行。

每当解析一列/行时,都应将其返回到“原始数组”。

为此,我创建了一个类,它将应用我指定的不同解析规则。获取解析规则效果很好。我目前陷入实际的文本转换/解析方面。

假设我有一个名为“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"
}
]

这里有两个问题:

  1. 它成功应用了解析规则(Trever 被 Oliver 替换)。但它只返回第一列,但我希望转换整个原始数组。
  2. 如果我从 apply() 方法中删除 1,则会收到以下错误:
Array to string conversion

在下面一行:

return preg_replace($this->pattern, $this->replacement, $table);

任何人都可以引导我走向正确的方向,以便我可以在任何列或所有列上执行解析规则,并将转换后的数据返回到原始数组吗?

最佳答案

我将重写 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;
}

Demo on 3v4l.org

关于PHP - 对嵌套数组执行解析规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56163950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com