从序列化数组MySQL中检索特定值

时间:2011-09-28 23:12:47

标签: php mysql wordpress denormalized

数据库结构如下:

id|metaKey|metaValue
--+-------+-----------------------------------
55|product|a:8:{s:3:"sku";s:0:"";s:8:"products";a:3:{i:1;a:3:{s:6:"option";s:1:"1";s:5:"price";s:5:"14.95";s:9:"saleprice";s:0:"";}i:2;a:3:{s:6:"option";s:0:"";s:5:"price";s:0:"";s:9:"saleprice";s:0:"";}i:3;a:3:{s:6:"option";s:0:"";s:5:"price";s:0:"";s:9:"saleprice";s:0:"";}}s:11:"description";s:124:"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";s:8:"shiprate";s:1:"A";s:8:"featured";s:2:"no";s:4:"sale";s:3:"yes";s:10:"cart_radio";s:1:"0";s:6:"optset";s:0:"";}

这是来自wordpress网站,我需要检索第一个“价格”值14.95,从存储在mysql中的序列化数组中检索特定值的最佳方法是什么?

2 个答案:

答案 0 :(得分:7)

创建查询,从SQL读取数据,unserialize()metaValue并像数组一样访问它。如果你需要在mysql中提取它,你也可以尝试使用正则表达式,但这是一个不太好的方法。

答案 1 :(得分:1)

使用unserialize()检索metaValue数据。

以下代码可以检索第一个价格值:

$result = mysql_query("SELECT * FROM tbl WHERE id=55");
$row = mysqLfetch_assoc($result);

$serial = $row['metaValue'];
$data = unserialize($serial);
echo $data['products'][1]['price'];

此行中的数据结构为:

array(8) {
  ["sku"]=>
  string(0) ""
  ["products"]=>
  array(3) {
    [1]=>
    array(3) {
      ["option"]=>
      string(1) "1"
      ["price"]=>
      string(5) "14.95"
      ["saleprice"]=>
      string(0) ""
    }
    [2]=>
    array(3) {
      ["option"]=>
      string(0) ""
      ["price"]=>
      string(0) ""
      ["saleprice"]=>
      string(0) ""
    }
    [3]=>
    array(3) {
      ["option"]=>
      string(0) ""
      ["price"]=>
      string(0) ""
      ["saleprice"]=>
      string(0) ""
    }
  }
  ["description"]=>
  string(124) "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
  ["shiprate"]=>
  string(1) "A"
  ["featured"]=>
  string(2) "no"
  ["sale"]=>
  string(3) "yes"
  ["cart_radio"]=>
  string(1) "0"
  ["optset"]=>
  string(0) ""
}