将由空数组

时间:2017-02-23 09:16:55

标签: php arrays

我有一个这样的数组:

Array
(
    [A] => 
    [B] => 700
    [C] => 422
    [F] => IDR
    [G] =>   5,945,193,025,500.00 
    [H] => 
)
Array
(
    [A] => 
    [B] => 700
    [C] => 421
    [F] => IDR
    [G] => 
    [H] =>   5,945,193,025,500.00 
)
Array
(
    [A] => 
    [B] => 
    [C] => 
    [F] => 
    [G] => 
    [H] => 
)
Array
(
    [A] => 
    [B] => 700
    [C] => 4945
    [F] => IDR
    [G] =>   406,630,911,282.00 
    [H] => 
)
Array
(
    [A] => 
    [B] => 700
    [C] => 228
    [F] => IDR
    [G] => 
    [H] =>   406,630,911,282.00 
)
Array
(
    [A] => 
    [B] => 
    [C] => 
    [F] => 
    [G] => 
    [H] => 
)

我想要这样的结果

Array
(
    [A] => 1
    [B] => 700
    [C] => 422
    [F] => IDR
    [G] =>   5,945,193,025,500.00 
    [H] => 
)
Array
(
    [A] => 1
    [B] => 700
    [C] => 421
    [F] => IDR
    [G] => 
    [H] =>   5,945,193,025,500.00 
)
Array
(
    [A] => 2
    [B] => 700
    [C] => 4945
    [F] => IDR
    [G] =>   406,630,911,282.00 
    [H] => 
)
Array
(
    [A] => 2
    [B] => 700
    [C] => 228
    [F] => IDR
    [G] => 
    [H] =>   406,630,911,282.00 
)

[A]处添加ID,并以空数组

分隔

此数组来自此代码:

$array = array_chunk($sheetData, 1); 
foreach($array as $chunk) { 
    foreach($chunk as $subarray) { 
        echo "<pre>"; 
        print_r($subarray); 
        echo "</pre>";
     } 
} 

1 个答案:

答案 0 :(得分:1)

<?php

$in =
[
    [
        'a'=> null,
        'b'=> 'foo'
    ],
    [],
    [
        'a'=> null,
        'b'=> 'bar'
    ],
    [
        'a'=> null,
        'b'=> 'baz'
    ],
    [],
    [
        'a'=> null,
        'b'=> 'bat'
    ]    
];

$out     = [];
$counter = 1;
foreach($in as $array) {
    if(empty($array)) {
        $counter++;
    } else {
        $array['a'] = $counter;
        $out[]      = $array;
    }
}

var_export($out);

输出:

array (
  0 => 
  array (
    'a' => 1,
    'b' => 'foo',
  ),
  1 => 
  array (
    'a' => 2,
    'b' => 'bar',
  ),
  2 => 
  array (
    'a' => 2,
    'b' => 'baz',
  ),
  3 => 
  array (
    'a' => 3,
    'b' => 'bat',
  ),
)