php - How to fill an array with a function, and use that array outside the function? -
i'am working in codeigniter (ci), , trying create nested set of category items dropdown list. create dropdown box, in ci need echo form_dropdown('name', $array, $selectedid)
.
here function create nested list array:
$categorydata = array(); function list_categories($cats, $sub = ''){ foreach($cats $cat){ //$cat['category']->id = $sub.$cat['category']->title; $categorydata[$cat['category']->id] = $sub.$cat['category']->title; if( sizeof($cat['children']) > 0 ){ $sub2 = str_replace('—→ ', '–', $sub); $sub2.= '–→ '; list_categories($cat['children'], $sub2); } } }
if var_dump($categorydata);
right after foreach
inside list_categories()
function, return array of nested sets. ok when using var_dump()
inside function. need this:
<?php list_categories($categories); var_dump($categorydata); ?>
and here empty array, here output:
array (size=0) empty
could tell me i'am doing wrong here ?
your function modifies local copy, should returned global scope. want achieve might done globals
("bad practice"), return
or references
.
try use references
:
function list_categories(&$result, $cats, $sub = ''){ // <- foreach($cats $cat){ //$cat['category']->id = $sub.$cat['category']->title; $result[$cat['category']->id] = $sub.$cat['category']->title; // <- if( sizeof($cat['children']) > 0 ){ $sub2 = str_replace('—→ ', '–', $sub); $sub2.= '–→ '; list_categories($result, $cat['children'], $sub2); // <- } } } $categorydata = array(); list_categories($categorydata, $categories); // <-
upd: in end, recusive function, references better (as me). sorry inconvinience.
Comments
Post a Comment