M K Wiro
M K Wiro

Reputation: 85

Remove nested array in nested foreach PHP

I have a problem in presenting data from a database using nested foreach. in the code that I worked on, I almost managed to provide data output from the transaction database as I expected in the form of a multidimensional array which in the second nested array contains the product sold and removes the duplicate data of the product sold.

and my problem is how to delete or not display the last nested array?

this is my code:

    public function resultSetFP()
{
  $this->execute();
  $res = $this->stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_ASSOC);
 foreach($res as $key => $value){
   foreach($value as $v){
      foreach($v as $b){
         $res[$key][$b]=$b;
      }
   }
 }
 return $res;
}

output code:

    'P2-6/01/2018/094909/0001' => 
    array (size=5)
      0 => 
        array (size=1)
          'Bid' => string 'Dagadu Bocah' (length=12)
      1 => 
        array (size=1)
          'Bid' => string 'HirukPikuk' (length=10)
      2 => 
        array (size=1)
          'Bid' => string 'HirukPikuk' (length=10)
      'Dagadu Bocah' => string 'Dagadu Bocah' (length=12)
      'HirukPikuk' => string 'HirukPikuk' (length=10)
  'P2-6/01/2018/095825/0002' => 
    array (size=4)
      0 => 
        array (size=1)
          'Bid' => string 'Dagadu' (length=6)
      1 => 
        array (size=1)
          'Bid' => string 'HirukPikuk' (length=10)
      'Dagadu' => string 'Dagadu' (length=6)
      'HirukPikuk' => string 'HirukPikuk' (length=10)

I expected to remove the third nested array leaving the data that I marked:

    'P2-6/01/2018/094909/0001' => 
        array (size=5)
//removing this array
          0 => 
            array (size=1)
              'Bid' => string 'Dagadu Bocah' (length=12)
          1 => 
            array (size=1)
              'Bid' => string 'HirukPikuk' (length=10)
          2 => 
            array (size=1)
              'Bid' => string 'HirukPikuk' (length=10)
//leaving this
          'Dagadu Bocah' => string 'Dagadu Bocah' (length=12)
          'HirukPikuk' => string 'HirukPikuk' (length=10)

Upvotes: 3

Views: 199

Answers (1)

serpentow
serpentow

Reputation: 196

Try that:

foreach ($res as $key => $value) {
    foreach ($value as $i => $v) {
        foreach ($v as $b) {
            $res[$key][$b] = $b;
        }

        unset($res[$key][$i]);
    }
}

Upvotes: 2

Related Questions