Question

I'm a little stumped on this one. I think the best way to ask it is by giving an example. So I have this array:

$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']   = ""

And what I'd like to do is to combine elements based on the Note AND Brand, so both of those have to be identical in order to qualify to be grouped together. So the output would be something like this:

$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']    = ""

Thank you DaneSoul for pushing me in the right direction. For anybody interested, here is the final code - I started with his code and did some modifications to make it work in my situation:

$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;
    }
Was it helpful?

Solution

<?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++;
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top