如何从$ arr1制作$ arr2

时间:2012-01-30 04:21:24

标签: php arrays

这可能并不困难,但是我花了半天时间,还没有解决。

以下是我的代码,RESERVE_COUNT是重复的数字。

$ arr1在这里,$ arr2与$ arr1没有任何关系,只是因为我想要$ arr2,所以我想从现有的$ arr1中赚取$ arr2。所以$ arr2起初并不存在。

如果不清楚,我会更好地解释,告诉我。

//$arr1:
array(
    [0] =>
    array(

        ['CLASS_MENU_SYMBOL'] => 'A'
        ['STAFF_ID'] => 3010120001
        ['STAFF_START_TIME'] => '09:00'
        ['STAFF_END_TIME'] => '10:00'
    )

    [1] =>
    array(

        ['CLASS_MENU_SYMBOL'] => 'B'
        ['STAFF_ID'] => 3010120001
        ['STAFF_START_TIME'] => '13:00'
        ['STAFF_END_TIME'] => '14:00'
    ) 

    [2] =>
    array(

        ['CLASS_MENU_SYMBOL'] => 'A'
        ['STAFF_ID'] => 3010120001
        ['STAFF_START_TIME'] => '09:00'
        ['STAFF_END_TIME'] => '10:00'
    ) 

    [3] =>
    array(

        ['CLASS_MENU_SYMBOL'] => 'A'
        ['STAFF_ID'] => 3010120001
        ['STAFF_START_TIME'] => '10:00'
        ['STAFF_END_TIME'] => '11:00'
    ) 
)

//$arr2:
array(
    [0] =>
    array(

        ['CLASS_MENU_SYMBOL'] => 'A'
        ['STAFF_ID'] => 3010120001
        ['STAFF_START_TIME'] => '09:00'
        ['STAFF_END_TIME'] => '10:00'
        ['RESERVE_COUNT'] => 2 //exactly same record appeared in $arr1 twice, so here is 2
    )

    [1] =>
    array(

        ['CLASS_MENU_SYMBOL'] => 'B'
        ['STAFF_ID'] => 3010120001
        ['STAFF_START_TIME'] => '13:00'
        ['STAFF_END_TIME'] => '14:00'
        ['RESERVE_COUNT'] => 1
    ) 

    [3] =>
    array(

        ['CLASS_MENU_SYMBOL'] => 'A'
        ['STAFF_ID'] => 3010120001
        ['STAFF_START_TIME'] => '10:00'
        ['STAFF_END_TIME'] => '11:00'
        ['RESERVE_COUNT'] => 1
    ) 
)

1 个答案:

答案 0 :(得分:1)

可能有很多方法。 例如:     

$arr2=array();

foreach($arr1 as $value)//$arr1 is the given array
{
    //create a key for the new Array to make it unique
  $key=md5(serialize($value));
  $value['RESERVE_COUNT']=1;

    //if an entry already exist, add RESERVE_COUNT
  if(isset($arr2[$key]))$value['RESERVE_COUNT']+=$arr2[$key]['RESERVE_COUNT'];

  $arr2[$key]=$value;
}
print_r($arr2);
?>

返回:

Array
(
    [450489089cc95e03d6c12dedb770a2a0] => Array
        (
            [CLASS_MENU_SYMBOL] => A
            [STAFF_ID] => 3010120001
            [STAFF_START_TIME] => 09:00
            [STAFF_END_TIME] => 10:00
            [RESERVE_COUNT] => 2
        )

    [8726c974e8d060b0dfdaab0aa29f5064] => Array
        (
            [CLASS_MENU_SYMBOL] => B
            [STAFF_ID] => 3010120001
            [STAFF_START_TIME] => 13:00
            [STAFF_END_TIME] => 14:00
            [RESERVE_COUNT] => 1
        )

    [003586db1308b821483d6bebc883a932] => Array
        (
            [CLASS_MENU_SYMBOL] => A
            [STAFF_ID] => 3010120001
            [STAFF_START_TIME] => 10:00
            [STAFF_END_TIME] => 11:00
            [RESERVE_COUNT] => 1
        )

)