从序列化数组中提取数据并输出到PHP

时间:2017-09-01 20:23:23

标签: php arrays serialization

我有这个:

            case 'Bulk Discount':
            $postMeta = get_post_meta($product->ID, 'o-discount');
            echo $postMeta[0];
            break;

'o-discount'是post_meta,返回:

'a:4:{s:6:"enable";s:1:"1";s:4:"type";s:10:"percentage";s:10:"rules-type";s:9:"intervals";s:5:"rules";a:1:{i:0;a:3:{s:3:"min";s:1:"3";s:3:"max";s:0:"";s:8:"discount";s:1:"5";}}}'

我想从序列化数组中回显数据,以便我可以显示它。

更新:

我曾尝试在上面的数组中使用unserialize,但它不会返回任何结果。当我使用下面找到的示例时,它返回“制造” - “加拿大”结果。

$mydata = 'a:5:{s:9:"engine_id";a:1:
{i:0;s:9:"300000225";}s:15:"transmission_id";a:1:
{i:0;s:6:"257691";}s:5:"plant";a:1:{i:0;s:23:"Oshawa, Ontario, 
Canada";}s:15:"Manufactured in";a:1:{i:0;s:6:"CANADA";}s:22:"Production 
Seq. Number";a:1:{i:0;s:6:"151411";}}';
$mydata = unserialize($mydata);
echo $mydata['Manufactured in'][0];

1 个答案:

答案 0 :(得分:1)

看起来你只是想尝试访问错误的数组键......

$mydata = 'a:4:{s:6:"enable";s:1:"1";s:4:"type";s:10:"percentage";s:10:"rules-type";s:9:"intervals";s:5:"rules";a:1:{i:0;a:3:{s:3:"min";s:1:"3";s:3:"max";s:0:"";s:8:"discount";s:1:"5";}}}';

$mydata = unserialize($mydata);

print_r($mydata); // See the structure

echo $mydata['rules'][0]['discount']; // 5

结果:https://eval.in/853921