How to flatten an array in PHP

Categorized as PHP Tagged

Try to use this code:

  public function flatten($array)
  {
          $flatArray = [];
  
          if (!is_array($array)) {
              $array = (array)$array;
          }
  
          foreach($array as $key => $value) {
              if (is_array($value) || is_object($value)) {
                  $flatArray = array_merge($flatArray, $this->flatten($value));
              } else {
                  $flatArray[0][$key] = $value;
              }
          }
  
          return $flatArray;
  }

Leave a reply

Your email address will not be published. Required fields are marked *