如何合并后续数组

时间:2019-02-27 13:33:33

标签: php laravel

我想合并以下后续数组。我怎样才能做到这一点? 条件:如果数组数等于3,则将后续数组合并到父级。

输入

 $data = [
  ['mango', 'orange', 'apple'],
  ['abc'],
  ['ctp'],
  ['pqr', 'cst', 'dtc'],
  ['cbx'],
  ['xyz'],
  ['atc'],
];

我想要输出如下:

  $data = [

  ['mango', 'orange', 'apple' 'additional' => [ ['abc'], ['ctp'] ] ],
  ['pqr', 'cst', 'dtc', 'additional' => [ ['cbx'],['xyz'],['atc'] ] ],

];

2 个答案:

答案 0 :(得分:5)

环绕数组并跟踪将数据合并到的位置。

foreach($data as $key => $d){
    if(count($d)>1){ 
        $mergeTo = $key; // store key where to merge to
        continue; // go to next item
    }
    $data[$mergeTo]["additional"][] = $d; // add value to $mergeTo
    unset($data[$key]); // unset the value from the main array
}
$data = array_values($data); // reset keys
var_export($data);

输出:

array (
  0 => 
  array (
    0 => 'mango',
    1 => 'orange',
    2 => 'apple',
    'additional' => 
    array (
      0 => 
      array (
        0 => 'abc',
      ),
      1 => 
      array (
        0 => 'ctp',
      ),
    ),
  ),
  1 => 
  array (
    0 => 'pqr',
    1 => 'cst',
    2 => 'dtc',
    'additional' => 
    array (
      0 => 
      array (
        0 => 'cbx',
      ),
      1 => 
      array (
        0 => 'xyz',
      ),
      2 => 
      array (
        0 => 'atc',
      ),
    ),
  ),
)

https://3v4l.org/BmXUZ

答案 1 :(得分:2)

尝试一下:

$newArr = [];
$tempArr = [];
$arrCount = count($data);
foreach($data as $item) {
    $arrCount--;
    if (count($item) > 2) {
        if (!empty($tempArr)) {
            $newArr[] = $tempArr;
        }
        $tempArr = $item;
        continue;
    }

    if (!empty($tempArr)) {
        $tempArr['additional'][] = $item;
    } else {
        $newArr[] = $item;
    }

    if ($arrCount <= 0) {
        $newArr[] = $tempArr;
    }
}

print_r($newArr);