让我快速了解一下,这是我的源数组:
Array (
[0] => Array (
[1] => Array (
[id] => 1
[category] => Men
[items] => Array (
[0] => Array (
[id] => 1
[name] => Shirt
[price] => 21.8
)
)
)
)
[1] => Array (
[1] => Array (
[id] => 2
[category] => Men
[items] => Array (
[0] => Array (
[id] => 2
[name] => Trousers
[price] => 10.9
)
)
)
)
[2] => Array (
[1] => Array (
[id] => 3
[category] => Men
[items] => Array (
[0] => Array (
[id] => 3
[name] => Hat
[price] => 1.9
)
)
)
)
[3] => Array (
[2] => Array (
[id] => 4
[category] => Women
[items] => Array (
[0] => Array (
[id] => 4
[name] => Bra
[price] => 24.5
)
)
)
)
.
.
.
我现在想要实现的是通过类似的category
将items
结合起来,如下所示:
{
"1": {
"id": 1,
"category": "Men",
"items": [
{
"id": 1,
"name": "Shirt",
"price": "5:52"
},
{
"id": 2,
"name": "Trousers",
"price": "3:01"
},
]
},
.
.
.
我已经尝试了几种带有parentId之类的方法,但无法绕过它。
知道如何得到这个吗?
这是第一次尝试:
$output = array();
foreach ($source as $data) {
foreach ($data as $categoryId => $item) {
if (!isset($output[$categoryId])) {
$output[$categoryId] = array(
'id' => $categoryId,
'category' => $item['category'],
'items' => array(),
);
}
$output[$categoryId]['items'] = array_merge(
$output[$categoryId]['items'],
$item['items']
);
}
}
您可能需要以不同的方式处理这些项,具体取决于源数组的每个元素中的项数。我也不太确定您对预期输出中的价格值有什么看法,因此您可能需要详细说明。
代码板:http://codepad.org/tY15P0Qa
你可以尝试这样的事情,其中$catalog_item
是你的初始数组,$new_catalog
你想要的数组:
$new_catalog = array( ) ;
foreach( $catalog_item as $grouping ) {
$mixed_cat_item = array_pop( $grouping ) ;
if( ! array_key_exists( $mixed_cat_item[ 'id' ], $new_catalog) {
$new_catalog[ $mixed_cat_item[ 'id' ] ] = array( 'id' => $mixed_cat_item[ 'id' ], 'category' => $mixed_cat_item[ 'category' ], 'items' => array( ) ) ;
}
$item = array_pop( $mixed_cat_item[ 'items' ] ) ;
$new_catalog[ 'id' ][ 'items' ][ ] = $item ;
}