如果找到两个连续的实例,则删除方括号的实例

Remove instance of square brackets, if found two successive instances

我有以下方式的数据:

{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }

现在,如果有两个连续的实例,如 [ [] ],我想删除方括号的实例,即 []

现在如果你看到上面的数据,你会看到 [] 的实例连续重复了两次。所以我想删除每个实例。

现在,我可以检查每个连续重复的两个实例并删除一个,就像这样

$text = '{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }';

echo preg_replace('/\[ \[+/', '[', $text);

现在,上面的代码是针对 [ 的。因此,要删除连续重复的 ] 实例,我将不得不再次重复相同的代码。

我想知道,有没有更好的方法可以达到同样的效果。同时,我可以解决这个问题,但如果将来我必须对任何其他角色做同样的事情怎么办?请在这里指导我。

怎么样:

echo str_replace(array('[ [', '] ]'), array('[', ']'), $text);

您正在处理 json 字符串。尝试字符串操作(使用正则表达式或其他)是禁忌的,因为 "over-matching".

很可能存在陷阱

虽然我不完全理解您的数据结构的可变性,但我可以通过将您的 json 字符串转换为数组然后使用数组函数安全地修改数据来提供一些临时指导。

考虑一下:

代码:(Demo)

$json='{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }';
$array=json_decode($json,true);  // convert to array
foreach($array as &$a){  // $a is modifiable by reference
    if(is_array($a) && isset($a[0]) && isset($a[0][0])){  // check if array and if two consecutive/nested indexed subarrays
        $a=array_column($a,0); // effectively shift deeper subarray up one level
    }
}
$json=json_encode($array);
echo $json;

输出:

{"id":"sugarcrm","text":"sugarcrm","children":[{"id":"accounts","text":"accounts","children":[{"id":"id","text":"id"},{"id":"name","text":"name"}]}]}

就此而言,如果您 知道 双嵌套索引的位置,那么您可以像这样访问它们而无需循环(或通过引用修改):

$json='{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }';
$array=json_decode($json,true);
$array['children']=array_column($array['children'],0);  // modify 2 known, nested, indexed subarrays
$json=json_encode($array);
echo $json;