最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to get specific attribute from DB

programmeradmin4浏览0评论
a:3:{
  i:0;a:2:{s:21:"wwsd_percent_discount";s:2:"10";s:25:"wwsd_minimum_discount_qrt";s:2:"20";}
  i:1;a:2:{s:21:"wwsd_percent_discount";s:2:"20";s:25:"wwsd_minimum_discount_qrt";s:2:"50";}
  i:2;a:2:{s:21:"wwsd_percent_discount";s:2:"30";s:25:"wwsd_minimum_discount_qrt";s:3:"100";}
}

I want to get 10, 20, 30 from wwsd_percent_discount.

I wrote this code:

$getId = $product->get_id();
global $wpdb;    
$result = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE post_id='$getId' AND meta_key ='wwsd_wholesale_discount_data'");

if ( !empty( $result ) ) {

    foreach ( $result as $r ) {
        echo "<br>".$r->meta_value;
    }
}
a:3:{
  i:0;a:2:{s:21:"wwsd_percent_discount";s:2:"10";s:25:"wwsd_minimum_discount_qrt";s:2:"20";}
  i:1;a:2:{s:21:"wwsd_percent_discount";s:2:"20";s:25:"wwsd_minimum_discount_qrt";s:2:"50";}
  i:2;a:2:{s:21:"wwsd_percent_discount";s:2:"30";s:25:"wwsd_minimum_discount_qrt";s:3:"100";}
}

I want to get 10, 20, 30 from wwsd_percent_discount.

I wrote this code:

$getId = $product->get_id();
global $wpdb;    
$result = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE post_id='$getId' AND meta_key ='wwsd_wholesale_discount_data'");

if ( !empty( $result ) ) {

    foreach ( $result as $r ) {
        echo "<br>".$r->meta_value;
    }
}
Share Improve this question edited Jan 24, 2020 at 21:40 nmr 4,5672 gold badges17 silver badges25 bronze badges asked Jan 24, 2020 at 20:33 user3748874user3748874 11 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 1

If the data you placed at the beginning of your question is the result of your database query (I'm unsure by how your question is worded), you will want to take that query result and use the PHP function unserialize() to convert that data to an array, then you can access your data from that array.

Your serialized data will become at array that looks like this:

Array
(
    [0] => Array
        (
            [wwsd_percent_discount] => 10
            [wwsd_minimum_discount_qrt] => 20
        )

    [1] => Array
        (
            [wwsd_percent_discount] => 20
            [wwsd_minimum_discount_qrt] => 50
        )

    [2] => Array
        (
            [wwsd_percent_discount] => 30
            [wwsd_minimum_discount_qrt] => 100
        )
)
发布评论

评论列表(0)

  1. 暂无评论