从多维数组搜索和匹配特定值php创建一个新数组


Create a new array from multidimensional array searching and matching a specific value php?

我一直在使用一个有点借贷系统的。它产生我从这个数组中得到的每日事务。'

   $trans_arr = array(
       0 => array(
             '2015-21-11',
              'credit#50',
             'debit#70'
             ),
      1 => array(
           '2015-21-11',
           'credit#80',
           'debit#30'
           ),
      3 => array(
         '2015-22-11',
         'credit#80',
         'debit#90'
        ),
      4 => array(
        '2015-22-11',
        'credit#30',
        'debit#80'
        ),
      5 => array(
        '2015-23-11',
        'credit#65',
        'debit#34'
        ),
   );

我的目标是将这个数组重新排列成这样,相同的日期成为一个键,找到日期的匹配数组成为它的后续数组。

   array(
     '2015-21-11' => array(
       0 => array(
         '2015-21-11',
         'credit#50',
         'debit#70'
       ),
      1 => array(
        '2015-21-11',
        'credit#80',
         'debit#30'
      )
    ),

   '2015-22-11' => array(
     0 =>array(
      '2015-22-11',
      'credit#80',
      'debit#90'
    ),
    1 => array(
      '2015-22-11',
      'credit#30',
      'debit#80'
    ),
  ),
 '2015-23-11' => array(
    0 => array(
      '2015-23-11',
      'credit#65',
      'debit#34'
      )
  ),

);

目前我无法按特定日期对交易进行分组。如果我可以将数组重新排列为我喜欢的数组,这将帮助我向用户显示特定日期的事务。

您只需遍历您的数组,然后在新数组中随意重新排列即可。它可能不是最快的代码,但它非常灵活且易于理解。

http://php.net/manual/en/control-structures.foreach.php

//create the array containing the newly sorted data
$trans_sorted = [];
//go through each element of our array
foreach ($trans_arr as $trans) {
   //check if entry with that date exists already 
   //$trans[0] is the date
   If (!isset($trans_sorted[$trans[0]])) {
      //if it does not exist yet, initialize an empty array
      $trans_sorted[$trans[0]] = [];
   }
   //add our transaction to this date
   $trans_sorted[$trans[0]][] = $trans;
}
//print_r($trans_sorted)