选择特定值之后的所有值,直到数组中的下一个特定值

时间:2018-10-29 23:35:03

标签: php arrays

我有一个普通数组,里面有很多数据。假设数组的结构如下:

$myArray = array( 'a','b','c','title1','d','e','f','title2','g','h','title3','i','title4','j','k' );

我需要提取此值并将所有值放在title()值之后,直到一个数组中的下一个title()值。像这样:

$newarray[0] = array('a','b','c');
$newarray[1] = array('d','e','f');
$newarray[2] = array('g','h');
$newarray[3] = array('i');
$newarray[4] = array('j','k');

@mickmackusa答案正常工作,但我需要使用title()作为批处理密钥,例如:

$newarray[0] = array('a','b','c');
$newarray[title1] = array('d','e','f');
$newarray[title2] = array('g','h');
$newarray[title3] = array('i');
$newarray[title4] = array('j','k');

2 个答案:

答案 0 :(得分:2)

执行迭代检查是否以title开头的字符串。这表示批次之间的断点。存储批次时,请重置该批次以进行下一次迭代。循环结束后,检查是否有最终/尚未存储的批次。

代码1:(Demo

$myArray = array( 'a','b','c','title1','d','e','f','title2','g','h','title3','i','title4','j','k' );
foreach ($myArray as $v) {
    if (strpos($v, 'title') !== 0) {
        $batch[] = $v;
    } elseif (!empty($batch)) {
        $result[] = $batch;
        $batch = [];
    }
}
if (!empty($batch)) {
    $result[] = $batch;
}

var_export($result);

或为每个批处理子数组使用显式键。

代码2:(Demo

$batch = 0;                          // set first batch key
foreach ($myArray as $v) {
    if (strpos($v, 'title') !== 0) {
        $result[$batch][] = $v;      // use explicit batch key
    } else {
        ++$batch;                    // increment batch key
    }
}
var_export($result);

输出:(两个代码片段都产生相同的结果)

array (
  0 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
  1 => 
  array (
    0 => 'd',
    1 => 'e',
    2 => 'f',
  ),
  2 => 
  array (
    0 => 'g',
    1 => 'h',
  ),
  3 => 
  array (
    0 => 'i',
  ),
  4 => 
  array (
    0 => 'j',
    1 => 'k',
  ),
)

问题更新后:

代码:(Demo

$batch = 0;                           // default value
foreach ($myArray as $v) {
    if (strpos($v, 'title') !== 0) {  // value is NOT a "title#"" string
        $result[$batch][] = $v;       // save with current batch value as 1st level key 
    } else {
        $batch = $v;                  // update batch value with "title#" string
    }
}
var_export($result);

答案 1 :(得分:0)

尝试一下,但是您必须对其进行优化

show