SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Wizard
    Join Date
    Jan 2005
    Location
    blahblahblah
    Posts
    1,447
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    problem with recursion

    Hi,

    I have tried numerous times to refactor the code below, but it sucks... and the version here is the best I could came up with.

    Could you please help me refine it and provide advice?

    PHP Code:
      public function getCars()
      {

        
    $this->listOfCars'';
        
        
    $this->buildListOfCars($this->allTheCars);//turns array into string
        
        
    return $this->listOfCars;//a string

      
    }
      
      protected function 
    buildListOfCars($allTheCars)
      {

        
        foreach(
    $allTheCars as $cars){
          
          if(
    is_array($cars)){
            
    $this->buildListOfCars($cars);
          }
          
          
    $this->listOfCars.= $cars;

        }
      
      } 
    Asd you can see, it's impossible to say if data will be an array, or a string I can add to my list of cars string.

    Regards,

    -jj.

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You can't concatenate an array to a string(well, and get a useful result that is)

    PHP Code:
          if(is_array($cars)){ 
            
    $this->buildListOfCars($cars); 
          } else {
           
    // scalar, concat ok
          
    $this->listOfCars.= $cars;


  3. #3
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You might consider just making the array 1 dimensional
    PHP Code:
    function array_flatten($array) {
        
    $flat = array();
        foreach (
    $array as $element) {
            if (
    is_array($element)) {
                
    $flat array_merge($flatarray_flatten($element));
            } else {
                
    $flat[] = $element;
            }
        }
        return 
    $flat;
    }

    echo 
    implode(','array_flatten($nested_arrays)); 


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •