0

我对这个有点难过。我认为最好的提问方式是举个例子。所以我有这个数组:

$RN[0]['Brand']  = "AC"
      ['Number'] = "1234"
      ['Note']   = "12 Volt"

$RN[1]['Brand']  = "AC"
      ['Number'] = "1235"
      ['Note']   = "12 Volt"

$RN[2]['Brand']  = "Ford"
      ['Number'] = "7722"
      ['Note']   = "12 Volt"

$RN[3]['Brand']  = "AC"
      ['Number'] = "1236"
      ['Note']   = ""

我想要做的是基于 Note AND Brand 组合元素,因此这两个元素必须相同才能有资格组合在一起。所以输出会是这样的:

$RN[0]['Brand']   = "AC"
      ['Numbers'] = array( "1234", "1235" )
      ['Note']    = "12 Volt"

$RN[1]['Brand']   = "Ford"
      ['Numbers'] = array( "7722" )
      ['Note']    = "12 Volt"

$RN[2]['Brand']   = "AC"
      ['Numbers'] = array( "1236" )
      ['Note']    = ""

感谢 DaneSoul 将我推向正确的方向。对于任何感兴趣的人,这里是最终代码 - 我从他的代码开始并做了一些修改以使其适用于我的情况:

$RN_new = array();
$i = 0;
$gotonext = 0;
foreach( $RN as $R ) {
    if ( isset( $RN_new ) && count( $RN_new ) > 0 ) {
        foreach( $RN_new as $key=>$RN_test ) {
            if ( $R['Brand'] == $RN_test['Brand'] && $R['Note'] == $RN_test['Note'] ) {
                $RN_new[$key]['Numbers'][] = $R['Number'];
                $gotonext = 1;
                }
            }
        }
    if ( $gotonext == 0 ) {
        $RN_new[$i]['Brand'] = $R['Brand'];
        $RN_new[$i]['Numbers'][] = $R['Number'];
        $RN_new[$i]['Note'] = $R['Note'];
        }
    $i++;
    $gotonext = 0;
    }
4

1 回答 1

1
<?php
$RN_new = array();
$i = 0;

foreach($RN as $RN_current){
  if($RN_current['Brand'] !== $RN_new[0]['Brand'] && 
     $RN_current['Note'] !== $RN_new[0]['Note']
  ){
     $RN_new[$i] = array('Brand' => $RN_current['Brand'], 
                         'Number' => array ($RN_current['Number']),
                         'Note' => $RN_current['Note']
                   );
  }
  else{
      $index = $i-1;
      $RN_new[$index]['Number'][] = $RN_current['Number']; 
  }
  $i++;
}
?>
于 2012-06-19T21:56:44.177 回答