如何将此函数转换为laravel函数

时间:2014-10-01 11:39:04

标签: php mysql laravel-4

如何将此递归函数转换为laravel fucntion。这是错误消息

" array_filter()期望参数1是数组,给定对象"

实际功能

$sql = "SELECT * FROM tasks";
$r = mysql_query($sql, $conn);
$arr = array();
while ($row = mysql_fetch_assoc($r))
   $arr[] = $row

function build($arrayIn, $parent)
{
    $makeFilter = function($p) {return function($x) use ($p) {return $x['parent'] == $p;};};
    $f = $makeFilter($parent);
    $these = array_filter($arrayIn, $f);
    $remaining = array_diff_assoc($arrayIn, $these);
    $ans = array();

    foreach($these as $cur)
    {
       $ans[$cur['text']] = build($remaining, $cur['id']);
    }
    return $ans ? $ans : null;
}

$tree = build($arr, 0)
echo_r($arr);
echo "becomes<br />";
echo_r($tree);

我的尝试无效

$arr = USER::all();

function build($arrayIn, $parent)
{
    $makeFilter = function($p) {return function($x) use ($p) {return $x['parent'] == $p;};};
    $f = $makeFilter($parent);
    $these = array_filter($arrayIn, $f);
    $remaining = array_diff_assoc($arrayIn, $these);
    $ans = array();

    foreach($these as $cur)
    {
       $ans[$cur['text']] = build($remaining, $cur['id']);
    }
    return $ans ? $ans : null;
}

$tree = build($arr, 0)
echo_r($arr);
echo "becomes<br />";
echo_r($tree);

1 个答案:

答案 0 :(得分:1)

如错误所示,当函数需要数组时,您正在使用对象。 您只需使用toArray()方法转换为数组:

$tree = build($arr->toArray(), 0);

http://laravel.com/docs/4.2/eloquent#converting-to-arrays-or-json