例如:我有一个关注数组
$array = array("abc","def","ghi", "jkl", "mno", "abc", "pqr", "stu", "vwy", "abc");
我需要为每次出现一个名为"abc"
的字符串分割这个数组我试过array_chunk
对我没有帮助..
答案 0 :(得分:7)
使用foreach的简单方法。只需遍历数组中的所有元素,然后将其拆分为条件。
<?PHP
$array = array("abc","def","ghi", "jkl", "mno", "abc", "pqr", "stu", "vwy", "abc");
$acc_arra = array();
$i=0;
foreach($array as $occurrences)
{
if($occurrences=='abc') //checking occurance
{
$i++;
}
else
{
if(!$acc_arra) //To start array from 0(if first element is 'abc')
{
$i=0;
}
$acc_arra[$i][]=$occurrences; //add to array
}
}
print_r($acc_arra);
<强>输出强>
Array
(
[0] => Array
(
[0] => def
[1] => ghi
[2] => jkl
[3] => mno
)
[1] => Array
(
[0] => pqr
[1] => stu
[2] => vwy
)
)
答案 1 :(得分:1)
php中没有使用值分割数组的直接函数,所以请使用foreach循环来分割数组。请找到一个示例函数来使用值分割数组。
<?php
$array = array("abc","def","ghi", "jkl", "mno", "abc", "pqr", "stu", "vwy", "abc");
function splitArray($array, $value = '') {
$returnArray = array();
$inc = 0;
if(is_array($array)) {
foreach($array as $arrayValue) {
if($value == $arrayValue) {
$inc++;
}
$returnArray[$inc][] = $arrayValue;
}
}
return $returnArray;
}
$finalArray = splitArray($array, 'abc');
print_r($finalArray);
?>
答案 2 :(得分:1)
这是通过首先将数组元素转换为字符串来实现的方法。 然后你可以使用正则表达式将其拆分。
简单方法
<?php
$array = array("abc","def","ghi", "jkl", "mno", "abc", "pqr", "stu", "vwy", "abc");
$string = implode(' ', $array);
$a = preg_split("/[abc]+/", $string);
print_r($a);
Array
(
[0] =>
[1] => def ghi jkl mno
[2] => pqr stu vwy
[3] =>
)
复杂方式
<?php
$array = array("abc","def","ghi", "jkl", "mno", "abc", "pqr", "stu", "vwy", "abc");
$string = implode(' ', $array);
$a = preg_split("/[abc]+/", $string);
$b = array();
$d = array();
for($i = 0; $i < count($a); $i++) {
if($a[$i] == NULL) continue;
$b[] = $a[$i];
}
for($i = 0; $i < count($b); $i++) {
//echo $b[$i] . PHP_EOL;
$c = explode(' ', $b[$i]);
for($ii = 0; $ii < count($c); $ii++) {
if($c[$ii] == NULL) continue;
$d[$i][] = $c[$ii];
}
}
print_r($d);
<强>输出强>
Array
(
[0] => Array
(
[0] => def
[1] => ghi
[2] => jkl
[3] => mno
)
[1] => Array
(
[0] => pqr
[1] => stu
[2] => vwy
)
)