Carlos
Carlos

Reputation: 1331

Recursive method fill array php laravel

I'm trying to create a recursive method to fill an array with each new item found.

function getUserUbigeoString($ubigeo_id){
    $ubigeoRepository = new \App\Repositories\UbigeoRepository();
    $ubigeos = array();

    $ubigeo = $ubigeoRepository->getUbigeo($ubigeo_id);

    if(!empty($ubigeo)){
        if($ubigeo->ubigeo_id == null){
            $ubigeos[] = $ubigeo->name;
        }

        $ubigeos[] = getUserUbigeoString($ubigeo->ubigeo_id);
    }

    return $ubigeos;
}

The objective of the code is to get an array fill with all the name of the ubigeos.

0 => ubigeo1
1 => ubigeo2
2 => ubigeo3
etc...

As of right now, i have tried placing the return many different locations, but the closest result i have gotten was:

array:1 [▼
  0 => array:1 [▼
    0 => array:2 [▼
      0 => "Port Dusty"
      1 => []
    ]
  ]
]

==========EDIT============ Structure of database ubigeos:

id  name     level ubigeo_id
----------------------------
3    ubigeo1  1     null
37   ubigeo2  2     3
55   ubigeo3  3     37

the output would be a simple array like so, which then i could implode into a comma separated string:

array:1 [
  0 => 'ubigeo1'
  1 => 'ubigeo2'
  2 => 'ubigeo3'
]

Upvotes: 0

Views: 1040

Answers (2)

Parithiban
Parithiban

Reputation: 1666

Use Can do it with lists method in laravel

Ex :

$ubigeoRepository->lists('ubigeo_id','id')->all();

Upvotes: 0

ejuhjav
ejuhjav

Reputation: 2710

so assuming that you really want to call this with function with an Ubigeo instance and only get the names from that and from the parent Ubigeo instances (i.e. calling the function with id 55 initially to get the result array), you can try something like this (I didn't want to modify your function call parameters - normally I would include the array as a function parameter instead of instantiating new one in each recursion step):

function getUserUbigeoString($ubigeo_id)
{
    $ubigeoRepository = new \App\Repositories\UbigeoRepository();
    $ubigeos = array();

    $ubigeo = $ubigeoRepository->getUbigeo($ubigeo_id);

    if(!empty($ubigeo))
    {
        if($ubigeo->ubigeo_id != null) {
            $ubigeos = getUserUbigeoString($ubigeo->ubigeo_id);
        }
        $ubigeos[] = $ubigeo->name;
    }

    return $ubigeos;
}

Upvotes: 1

Related Questions