开发者

Add items to nested arrays

I use this code to create arrays inside array.

array_push($lists, $list);

And then I try to add items to neste开发者_如何学编程d arrays:

array_push($lists[$list], $item);

But get an error:

Warning: array_push() expects parameter 1 to be array, null given in V:\home\...

$list is some name, $item is an object.

How to fix the problem?


It's because the first parameter is null. Assuming you are using default indexes, you could do something like:

$numItems = array_push($lists,$list);
array_push($lists[$numItems-1],$item)


This pushes $list at the end of $lists and gives it an integer key:

array_push($lists, $list);

This tries to access a string key into $lists, which does not exist:

$lists[$list]

so the return value is null. In the end, it's as if you did

array_push(null, $item);

For a solution, we need to know if you are doing anything on $lists apart from pushing onto it. If you are not, then:

$pushed_id = array_push($lists, $list) - 1;
array_push($lists[$pushed_id], $item);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜