Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 523
M K Wiro Avatar asked Apr 20 '26 05:04

M K Wiro


1 Answers

Try that:

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

        unset($res[$key][$i]);
    }
}
like image 119
serpentow Avatar answered Apr 22 '26 21:04

serpentow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!