Opt*_*ime 2 php arrays string substring comma
我下面有一个字符串,
$string = "div-item-0,4,maintype:menu| heading: Quick Link| isactive:1,0,0, div-item-1,4,maintype:text| heading:Image| isactive:1,4,0, div-item-2,4,maintype:social| heading:Social| isactive:1,8,0";"
Run Code Online (Sandbox Code Playgroud)
现在,我想将此字符串转换为子字符串,使其成为数组元素,如下所示,
$array = [
"div-item-0,4,maintype:menu| heading: Quick, Link| isactive:1,0,0",
"div-item-1,4,maintype:text| heading:Image| isactive:1,4,0",
"div-item-2,4,maintype:social| heading:Social| isactive:1,8,0",
];
Run Code Online (Sandbox Code Playgroud)
在计数了五个逗号后$string,子字符串将转换为数组元素。
如何使用PHP做到这一点?
您可以使用该array_chunk方法解决此问题
<?php
$string = "
div-item-0,4,maintype:menu| heading: Quick Link| isactive:1,0,0,
div-item-1,4,maintype:text| heading:Image| isactive:1,4,0,
div-item-2,4,maintype:social| heading:Social| isactive:1,8,0";
$temp = explode(',', $string); // just create one big array
$temp = array_chunk($temp, 5); // group the array per 5 parts
foreach($temp as &$value) $value = trim(implode(',', $value)); // recombine to one string
var_dump($temp);
Run Code Online (Sandbox Code Playgroud)