这里的 indexAction 我必须调用 subcat 函数来递归获取类别和子类别的列表,否则它不起作用。
注意 subcat 会自行调用。
如何在indexAction外编写subcat函数?并从 IndexAction 中调用它。这样做,我可以重复使用 subcat 。
class ItemsController implements ControllerProviderInterface {
public function connect(Application $app) {
$controllers = $app['controllers_factory'];
$controllers
->get('/', array($this, 'indexAction'))
->bind('items_index');
return $controllers;
}
public function indexAction(Application $app) {
$categorias = array();
function subcat($idPadre, array & $categorias, $app) {
$sql = 'SELECT id, categoria FROM categorias' .
' WHERE id_padre=' . $idPadre .
' ORDER BY categoria';
$query = $app['db']->fetchAll($sql);
foreach ($query as $valor) {
$a = subcat($valor['id'], $categorias, $app);
$lista[$valor['id'].'-'.$valor['categoria']] = $a;
}
return $lista;
};
$estructura = subcat(0, $categorias, $app);
print_r($estructura);
return '';
}
}
答案 0 :(得分:0)
您可以将可重复使用的代码注册为服务。你应该在这里找到你需要的任何东西:LINK
答案 1 :(得分:0)
我解决了这项服务,其中$ app [' Categorias.lista']包含所有类别:
$app['Categorias.idPadre'] = 0;
$app['Categorias.lista'] = '';
$app['Categorias'] = $app->share(function ($app) {
function subcat($idPadre, $app) {
$sql = 'SELECT id, categoria FROM categorias' .
' WHERE id_padre=' . $idPadre .
' ORDER BY categoria';
$query = $app['db']->fetchAll($sql);
foreach ($query as $valor) {
$lista[$valor['id'].'-'.$valor['categoria']] = subcat($valor['id'], $app);
}
return $lista;
};
$app['Categorias.lista'] = subcat($app['Categorias.idPadre'], $app);
});
然后我在我的indexAction方法中测试它:
$app['Categorias.idPadre'] = 0;
$app['Categorias'];
print_r($app['Categorias.lista']);
和print_r在我的例子中给出了这个:
Array
(
[2-capacitor] => Array
(
[14-ceramico] =>
[12-electrolitico] =>
[13-multicapa] =>
[16-polipropileno] =>
[15-polyester] =>
)
[3-circuito impreso] =>
[4-diodo] =>
[1-resistencia] => Array
(
[11-ceramica] =>
[5-metal] => Array
(
[8-1W] =>
[9-2W] =>
[10-3W] =>
[7-mini] =>
)
)
[20-teclado] =>
[21-transformador] =>
[17-transistor] => Array
(
[18-bipolar] =>
[19-mosfet] =>
)
)
答案 2 :(得分:0)
您所要做的就是让您的内部函数成为ItemsController中的私有函数。
class ItemsController implements ControllerProviderInterface {
public function connect(Application $app) {
$controllers = $app['controllers_factory'];
$controllers
->get('/', array($this, 'indexAction'))
->bind('items_index');
return $controllers;
}
public function indexAction(Application $app) {
$categorias = array();
$estructura = $this->subcat(0, $categorias, $app);
print_r($estructura);
return '';
}
private function subcat($idPadre, array & $categorias, $app) {
$sql = 'SELECT id, categoria FROM categorias' .
' WHERE id_padre=' . $idPadre .
' ORDER BY categoria';
$query = $app['db']->fetchAll($sql);
foreach ($query as $valor) {
$a = $this->subcat($valor['id'], $categorias, $app);
$lista[$valor['id'].'-'.$valor['categoria']] = $a;
}
return $lista;
}
}