所以我正在尝试将一些Wordpress与后端集成。他们的MySQL模式不是很好,特别是当你添加Woocommerce时。
我想出了以下查询:
SELECT wp.*
FROM wp_postmeta wp
INNER JOIN (SELECT post_id
FROM wp_postmeta
WHERE ( `meta_key` = '_shipping_method'
AND `meta_value` = 'free_shipping' )
OR ( `meta_key` = '_order_items'
AND `meta_value` LIKE '%search%' )) a
ON a.post_id = wp.post_id
ORDER BY wp.post_id DESC
要在此表上运行 https://i.stack.imgur.com/qMHQp.jpg 为某些人选择正确的东西。
现在,当我在 PHP 中var_dump这个时,结果是这样的(截断) - http://pastebin.com/WR3byT8k
有什么方法可以将其正确映射到数组,以便我可以使用简单的东西,例如:
echo $content['_billing_first_name'];
echo $content['_billing_last_name'];
这将输出:
John
Citizen
请记住,所有内容都是动态的,所以我不能只使用行号。
如果您需要检索一组固定的元键(不一定是固定顺序),则可以使用类似于数据透视表的技术在查询本身中执行此操作。
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,如果你有一个要检索的元 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);
要获得所有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);