【发布时间】:2016-12-09 03:34:17
【问题描述】:
我正在尝试将数组组合成一个单一的多维数组。可能有超过 5 个数组需要组合,所以我需要一个代码来自动组合所有数组,无论它们有多少。我试过array_merge,但它需要以逗号格式的参数手动定义数组。
要转换的代码是:
Array
(
[id] => 1
[name] => Item 1
[slug] => item-slug-1
[parent] => 0
)
Array
(
[id] => 2
[name] => Item 2
[slug] => item-slug-2
[parent] => 1
)
Array
(
[id] => 3
[name] => Item 3
[slug] => item-slug-3
[parent] => 2
)
Array
(
[id] => 4
[name] => Item 4
[slug] => item-slug-4
[parent] => 3
)
Array
(
[id] => 5
[name] => Item 5
[slug] => item-slug-5
[parent] => 3
)
这就是我想要的样子:
Array
(
[0] => Array
{
[id] => 1
[name] => Item 1
[slug] => item-slug-1
[parent] => 0
}
[1] => Array
{
[id] => 2
[name] => Item 2
[slug] => item-slug-2
[parent] => 1
}
[2] => Array
{
[id] => 3
[name] => Item 3
[slug] => item-slug-3
[parent] => 2
}
[3] => Array
{
[id] => 4
[name] => Item 4
[slug] => item-slug-4
[parent] => 3
}
[4] => Array
{
[id] => 5
[name] => Item 5
[slug] => item-slug-5
[parent] => 3
}
)
数组的生成方式如下:
-
我收到来自服务器的响应 JSON,如下所示:
[{"slug":"item-slug-1","name":"Item 1","id":1},{"slug":"item-slug-2","name":"Item 2","id":2},{"slug":"item-slug-3","name":"Item 3","id":3,"children":[{"slug":"item-slug-4","name":"Item 4","id":4},{slug":"item-slug-5","name":"Item 5","id":5}]}] -
我对 JSON 进行解码,然后将其转换为这样的数组:
$categories_obj = json_decode( $_POST['order'] ); $categories_arr = json_decode(json_encode( $categories_obj ), true); -
我创建了一个遍历每个项目的函数,以便更容易插入到我的数据库中:
function walk_and_update($data, $parent = 0, $count = 0) { if( is_array($data) ) { $combine = array(); /* The arrays are generated here */ foreach( $data as $key => $row ) { $formatted = array( 'id' => $row['id'], 'name' => $row['name'], 'slug' => $row['slug'], 'parent' => $parent ); print_r( $formatted ); /* My SQL update is here */ if( isset( $row['children'] ) ) { walk_and_update( $row['children'], $row['id'], $count ); } } }}
-
然后我使用这样的函数:
walk_and_update( $categories_arr );
【问题讨论】:
-
你尝试了什么?显示您的代码。
-
如果你仔细阅读,我提到过尝试array_merge。您还需要查看代码吗?
-
array_merge无法帮助您获得预期的输出。看看我的回答。 -
$categories_arr = json_decode(json_encode( $categories_obj ), true);的目的是什么? -
它将所有对象转换为数组。这可能看起来很奇怪,但它确实有效。
标签: php arrays multidimensional-array