Someone
Someone

Reputation: 10575

How to build this kind of Logic using arrays in PHP

I have an array which consists of this set of items

array(3) {
  [0]=>
  array(4) {
    ["Field1"]=>
    string(8) "80000007"
    ["Field2"]=>
    string(16) "O70000006"
    ["Field3"]=>
    string(0) ""
    ["Field4"]=>12345
    string(0) ""
   }
  [1]=>
  array(4) {
    ["Field1"]=>
    string(8) "80000008"
    ["Field2"]=>
    string(16) "O70000007"
    ["Field3"]=>
    string(0) ""
    ["Field4"]=>78965
    string(0) ""
  }
  [2]=>
   array(4) {
    ["Field1"]=>
    string(8) "80000009"
    ["Field2"]=>
    string(16) "H80000006"
    ["Field3"]=>
    string(0) ""
    ["Field4"]=>12345
    string(0) ""
  }
}

Now my question is Iam trying to display only the items once from array or trying to filter the array in such a way if the "Field2" has a value starting with "O" or "H" and their "Field4 " value should be different . If the "Field4" value is same for the each of the row then we dont display that row or array item . For eaxample from the above array we will get 2 items as follows

1)80000007 O70000006 12345
2)80000008 O70000007 78965

//we are not displaying the 3rd Item because The "Field4 " is same . we display only once

 foreach ($resultset  as $key => $value){           
            echo $key."<br>"; ///  outputs 0,1,2
            echo $value['Field2']."<br>"; // outputs O70000006, O70000007, H80000006
}

Upvotes: 0

Views: 103

Answers (2)

Chriszuma
Chriszuma

Reputation: 4557

So... you just want some way to skip rows whose Field4 has already been printed?

Set up an array to hold all the previously printed Field4s, and check against that before printing anything. Something like this:

$field4s = array();
foreach ($resultset  as $key => $value){    
            $field4 = $value['Field4'];
            if (($field4[0] == 'O' || $field4[0]=='H') && !in_array($field4 , $field4s) {
                array_push($field4s, $field4);
                echo $field4;
            }
}

Upvotes: 0

Naftali
Naftali

Reputation: 146300

function getField2_removeDupeField4($arr){
     $f4 = array();
     $f2 = array();
     foreach($arr as $array){
          if(in_array($array['Feild4'], $f4){   continue;  }
          $firstChar = substr($array['Feild2'], 0, 1);
          if($firstChar == 'O' || $firstChar == 'H'){
               $f2[] = $array;
               $f4[] = $array['Feild4'];
          }
     }
     return $f2;
}

So to get the array you want:

$new_arr = getField2_removeDupeField4($orig_arr);

Upvotes: 1

Related Questions