在php中我正在开发一个“单个产品页面”,其中每个字段捕获并显示从数据库中检索的数据。我偶然发现了“产品属性”数据库字段,因为它存储了这个值:
a:1:{s:10:"pa_flacone";a:6:{s:4:"name";s:10:"pa_flacone";s:5:"value";s:0:"";s:8:"position";s:1:"0";s:10:"is_visible";s:1:"1";s:12:"is_variation";i:1;s:11:"is_taxonomy";i:1;}}
坦率地说,我不知道如何管理以提取值并在php专用字段上复制它们。它看起来像Json格式。有关如何解码此信息并以php形式报告的任何帮助吗?
答案 0 :(得分:2)
您可以使用WP专用函数maybe_unserialize()
,因为您的字符串是序列化数组:
$serialized_string = 'a:1:{s:10:"pa_flacone";a:6:{s:4:"name";s:10:"pa_flacone";s:5:"value";s:0:"";s:8:"position";s:1:"0";s:10:"is_visible";s:1:"1";s:12:"is_variation";i:1;s:11:"is_taxonomy";i:1;}}';
// Unserializing this string
$data_array = maybe_unserialize( $serialized_string );
// Output for test
echo '<pre>'; print_r( $data_array ); echo '</pre>';
我会得到这个:
Array
(
[pa_flacone] => Array
(
[name] => pa_flacone
[value] =>
[position] => 0
[is_visible] => 1
[is_variation] => 1
[is_taxonomy] => 1
)
)
但是这是一些使用get_post_meta()函数可以反序列化的产品元数据:
Set your product ID
$product_id = 40;
// Get the data (last argument need to be on "false" for serialized arrays)
$attributes_array = get_post_meta( $product_id, '_product_attributes', false);
// Output for test
echo '<pre>'; print_r( $attributes_array ); echo '</pre>';
您将获得相同的输出。
要完成,您可以通过WC_Product
对象获取此数据,以使用此类的所有可用方法:
// Set your product ID
$product_id = 40;
// Get the WC_Product object
$product = wc_get_product( $product_id );
// Using WC_Product method get_attributes()
$product_attributes = $product->get_attributes();
// Output for test
echo '<pre>'; print_r( $product_attributes ); echo '</pre>';
这次你会得到一些不同的东西。所有属性数据都存储在WC_Product_Attribute
个对象中,您应该使用此类的可用方法来访问数据:
// Set your product ID
$product_id = 40;
// Get the WC_Product object
$product = wc_get_product( $product_id );
// Using WC_Product method get_attributes()
$product_attributes = $product->get_attributes();
// Iterating through each WC_Product_attribute object
foreach( $product_attributes as $attribute_taxonomy => $product_attribute){
// get the name (for example)
$name = $product_attribute->get_name()
// Access to the data in an array of values
$attribute_data = $product_attribute->get_data();
}