问题
I am using Laravel 4
with MySQL
back-end.
I want to store records of a nested array
into database using recursive function
.
The input array is as below :
Array
(
[0] => Array
(
'id' => 561,
'type' => 'q',
'subtype' => 'boolean',
'title' => 'Did you..?',
'parent' => 560,
'created_at' => '2014-07-09 09:45:50',
'updated_at' => NULL,
'deleted_at' => NULL,
'children' => Array
(
[0] => Array
(
'id' => 562,
'type' => 'o',
'subtype' => NULL,
'title' => 'Yes',
'parent' => 561,
'created_at' => '2014-07-09 09:45:50',
'updated_at' => NULL,
'deleted_at' => NULL,
'children' => Array
(
)
)
[1] => Array
(
'id' => 563,
'type' => 'answer',
'subtype' => NULL,
'title' => 'No',
'parent' => 561,
'created_at' => '2014-07-09 09:45:50',
'updated_at' => 'NULL',
'deleted_at' => NULL,
'children' => Array
(
)
)
)
)
)
The recursive function
I am using store the records into the database is as below :
public function addRecursiveChildren(array $surveychildren, $parentid, $userid){
foreach ($surveychildren as $item)
{
/* Error : HTTPRequest Error :: 500: {"error":{"type":"ErrorException","message":"Cannot use a scalar value as an array
Error is in the statement below in the second recursion when child is passes as an input.
*/
$item['survey_id'] = $item['id'];
$item['user_id'] = $userid;
$item['id'] = null;
$item['parent'] = $parentid;
$routine = routine::create($item);
if(count($item["children"]) > 0)
{
foreach ($item["children"] as $child)
{
/* The $child I found is as below :
$child = array(
'id' => 562,
'type' => 'o',
'subtype' => NULL ,
'title' => 'Yes',
'parent' => 561,
'created_at' => '2014-07-09 09:45:50',
'updated_at' => NULL,
'deleted_at' => NULL,
'children' => Array
(
)
);
*/
RoutineRepository::addRecursiveChildren($child, $routine->id, $userid);
}
}
}
}
Edit :
I know that cause of error is the $child
I am passing as an input array
to the recursive function
above :
The $child
is something like this :
array(
'id' => 562,
'type' => 'o',
'subtype' => NULL ,
'title' => 'Yes',
'parent' => 561,
'created_at' => '2014-07-09 09:45:50',
'updated_at' => NULL,
'deleted_at' => NULL,
'children' => Array
(
)
)
Instead of this if $child
will be something like this :
Array
(
[0] =>
array(
'id' => 562,
'type' => 'o',
'subtype' => NULL ,
'title' => 'Yes',
'parent' => 561,
'created_at' => '2014-07-09 09:45:50',
'updated_at' => NULL,
'deleted_at' => NULL,
'children' => Array
(
)
)
)
Then there will be no error.
Can anybody help me to overcome it?
Thanks.
回答1:
This should work
class Routine extends \Eloquent
{
// The relation
public function subRoutine()
{
return $this->hasMany('Routine', 'parent');
}
public function saveSubroutine(array $children)
{
foreach($children as $childData)
{
$child = new self($childData);
$this->subRoutine()->save($child);
$child->saveSubroutine($childData['children']);
}
}
}
$routine = Routine::create($data);
$routine->saveSubroutine($data['children']);
来源:https://stackoverflow.com/questions/24989245/php-laravel-recursive-function-with-nested-array