如果您有一组需要检索的固定元键(不一定是固定顺序),您可以使用类似于数据透视表的技术在查询本身中执行此操作。
SELECT
post_id,
MAX(CASE WHEN meta_key = '_billing_first_name' THEN meta_value ELSE NULL END) AS _billing_first_name,
MAX(CASE WHEN meta_key = '_billing_last_name' THEN meta_value ELSE NULL END) AS _billing_last_name,
MAX(CASE WHEN meta_key = '_some_other_attribute' THEN meta_value ELSE NULL END) AS _some_other_attribute,
MAX(CASE WHEN meta_key = '_another_attribute' THEN meta_value ELSE NULL END) AS _another_attribute,
...
...
FROM wp_post_meta
GROUP BY post_id
这些CASE
语句确定您要提取的参数并将其分配给列。它们被包装在MAX()
聚合中,只是为了消除键不匹配时导致的 NULL,将其折叠成单行,每个属性都有列,而不是多行,其中大部分是 NULL 值。
如果做不到这一点(如果您的属性集意外变化),您将需要在代码中进行迭代。不过那会很乱。
在 PHP 中:
使用 PHP,如果您有一个要检索的 meta post 键数组,您可以遍历所有行,如果meta_key
是您想要的,则将其存储meta_value
到一个数组中:
// Assumes your WP query results are already stored into the array $your_db_rows
// Will hold your final processed results
$output = array();
// If you want only a specific set of meta_key names rather than all meta_key names
$keys_you_want = array('_billing_first_name','_billing_last_name','_some_other_attribute');
// Loops over the result set
foreach ($your_db_rows_array as $row) {
// If the current row holds one of the meta_key you are looking for
if (in_array($row['meta_key'], $keys_you_want)) {
// Put it onto the output array using the meta_key as the array key
$output[$row['meta_key'] = $row['meta_value'];
}
// Otherwise do nothing...
}
var_dump($output);
要得到 all meta_key
,只需省略in_array()
测试和$keys_you_want
数组。这会将meta_key
遇到的每个存储到$output
.
// Loops over the result set for all values of meta_key, not a specific set
foreach ($your_db_rows_array as $row) {
// Put it onto the output array using the meta_key as the array key
$output[$row['meta_key'] = $row['meta_value'];
}
var_dump($output);