自从
MySQL5.7.22
你可以用
JSON_OBJECTAGG(key, value)
:
SELECT post_id, JSON_OBJECTAGG(meta_key, meta_value) AS meta_data
FROM wp_postmeta
WHERE post_id IN (SELECT id from wp_posts WHERE post_type = 'product')
GROUP by post_id
这个会回来的
meta_data
作为json_对象
key: value
对:
post_id | meta_data
2549 | {"_sku": "HCS-DGMP", "_weight": "0.50", "_virtual": "no", "_featured": "no", "_sale_price": null, "_tax_status": "taxable", "_visibility": "visible", "total_sales": "0", "_regular_price": "18.99", "_product_attributes": "a:0:{}"}
Demo
如果服务器不支持
JSON_OBJECTAGG()
,我将使用一个PHP解决方案:
$postIds = array_unique(array_column($dbResult, 'post_id'));
$posts = [];
foreach ($postIds as $id) {
$posts[$id] = (object)['id' => $id];
}
foreach ($dbResult as $row) {
$posts[$row->post_id]->{$row->meta_key} = $row->meta_value;
}
echo json_encode(array_values($posts), JSON_PRETTY_PRINT);
结果:
[
{
"id": "2549",
"total_sales": "0",
"_virtual": "no",
"_tax_status": "taxable",
"_visibility": "visible",
"_featured": "no",
"_weight": "0.50",
"_sku": "HCS-DGMP",
"_product_attributes": "a:0:{}",
"_regular_price": "18.99",
"_sale_price": ""
}
]
Demo
只要您不处理数千行,我就不会担心性能。