我有一个这样的数组:
array:3 [▼
0 => array:7 [▼
"feed_key" => "URL"
"table_key" => "feed_url"
"table_name" => "data_feeds"
]
1 => array:7 [▼
"feed_key" => "network_id"
"table_key" => "name"
"table_name" => "networks"
]
2 => array:7 [▼
"feed_key" => "product_name"
"table_key" => "product_description"
"table_name" => "products"
]
]
这可以包含许多数组,其中table_name(s)值以任何顺序重复。
我想要做的是按表名对数组进行分组,然后重新格式化为:
$data = [
'products' => [
'some_table_key' => 'some_field_key',
'another_table_key' => 'another_field_key',
],
'networks' => [
'some_table_key' => 'some_field_key',
'another_table_key' => 'another_field_key',
]
// .. and so on
];
使用php7最干净的方法是什么?如果可能的话,避免使用foreach。
答案 0 :(得分:1)
这很简单,可以使用foreach
完成(我不确定你为什么要避免它)
$result = [];
foreach($original_data as &$data){
$result[$data['table_name']] = [
$data['table_key'] => $data['feed_key']
];
}
这会给你:
array (size=3)
'data_feeds' =>
array (size=1)
'feed_url' => string 'URL' (length=3)
'networks' =>
array (size=1)
'name' => string 'network_id' (length=10)
'products' =>
array (size=1)
'product_description' => string 'product_name' (length=12)