基于条件的php从一个数组创建多个数组

时间:2014-04-26 09:50:13

标签: php arrays

初始数组

Array
(
[0] => Array
    (
        [RecordDay] => 23
        [Amount] => 1.50
        [DocumentName] => bank stmt
        [DocumentNumber] => 1
    )
[1] => Array
    (
        [RecordDay] => 17
        [Amount] => 0.21
        [DocumentName] => invoice
        [DocumentNumber] => 2
    )
[2] => Array
    (
        [RecordDay] => 17
        [Amount] => 1.00
        [DocumentName] => invoice
        [DocumentNumber] => 2
    )
)

在所有子阵列中,[RecordDay][DocumentName][DocumentNumber]都需要创建新数组。

对于密钥[1][2] [RecordDay][DocumentName][DocumentNumber]是相同的。

所以结果想得到这个

Array
(
[0] => Array
    (
        [RecordDay] => 23
        [Amount] => 1.50
        [DocumentName] => bank stmt
        [DocumentNumber] => 1
    )
)

Array
(
[0] => Array
    (
        [RecordDay] => 17
        [Amount] => 0.21
        [DocumentName] => invoice
        [DocumentNumber] => 2
    )

[1] => Array
    (
        [RecordDay] => 17
        [Amount] => 1.00
        [DocumentName] => invoice
        [DocumentNumber] => 2
    )
)

但不知道该怎么做

像这样制作

$first_loop = true;

foreach($initial_array as $key => $one_dimensional_array){

  if($first_loop == true){
  $new_array1['RecordDay'][] = $one_dimensional_array['RecordDay'];
  $first_loop = false;
  }

  if($first_loop == false){

  if( in_array( $one_dimensional_array['RecordDay'], $new_array1['RecordDay'] ) ){
  $new_array1['RecordDay'][] = $one_dimensional_array['RecordDay'];
  }
  else{
  $new_array2['RecordDay'][] = $one_dimensional_array['RecordDay'];
  }

  }//if($first_loop == false){

}//foreach($initial_array as $key => $one_dimensional_array){

GOT

Array
(
[RecordDay] => Array
    (
        [0] => 23
        [1] => 23
    )

[DocumentName] => Array
    (
        [0] => bank stmt
        [1] => bank stmt
    )

[DocumentNumber] => Array
    (
        [0] => 1
        [1] => 1
    )

)

Array
(
[RecordDay] => Array
    (
        [0] => 17
        [1] => 17
    )

[DocumentName] => Array
    (
        [0] => invoice
        [1] => invoice
    )

[DocumentNumber] => Array
    (
        [0] => 2
        [1] => 2
    )

)

但这不是想要的。有什么需要改变的想法吗?

1 个答案:

答案 0 :(得分:2)

试试这个,

$temp_array=array();
foreach($initial_array as $arr){
    $temp_array[$arr['RecordDay'].",".$arr['DocumentNumber'].",".$arr['DocumentName']] []=$arr;  //here it will **ADD** a new array in a key 'RecordDay,DocumentNumber,DocumentName' format. e.g. [23,1,'bank stmt'] , [17,2,'invoice'].


}

现在您需要处理$temp_array以获取单个数组

foreach ($temp_array as $separate_array){
    print_r($separate_array); //process your new array here one by one.
}

正在使用 DEMO