2

例如:我有一个以下数组
$array = array("abc","def","ghi", "jkl", "mno", "abc", "pqr", "stu", "vwy", "abc");

而且我需要为每次出现的字符串拆分这个数组,"abc" 我试过array_chunk对我没有帮助..

4

3 回答 3

6

使用 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
        )

)
于 2013-09-02T05:11:00.160 回答
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);
?>
于 2013-09-02T05:18:56.907 回答
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
        )

)
于 2013-09-02T05:21:04.403 回答