【问题标题】:PHP unserialize function get any number from 0-9PHP反序列化函数获取0-9之间的任意数字
【发布时间】:2012-12-06 21:59:07
【问题描述】:

我需要使用反序列化 php 函数获取产品 ID。我有这段文字

a:1:{i:4;a:17:{s:8:"quantity";i:1;s:10:"product_id";i:5196;s:11:"category_id";s:3:"209";s:5:"price";d:1;s:3:"tax";s:5:"18.00";s:6:"tax_id";s:1:"1";s:11:"description";s:0:"";s:12:"product_name";s:4:"test";s:11:"thumb_image";s:0:"";s:3:"ean";s:0:"";s:10:"attributes";s:6:"a:0:{}";s:16:"attributes_value";a:0:{}s:6:"weight";s:6:"0.0000";s:9:"vendor_id";s:1:"0";s:5:"files";s:6:"a:0:{}";s:14:"freeattributes";s:6:"a:0:{}";s:25:"dependent_attr_serrialize";s:6:"a:0:{}";}}

我通过这个 PHP 代码得到 product_id:

$rslt = unserialize($data);
echo $rslt[4]["product_id"]);

所以我的问题是有没有办法做类似echo $rslt[x]["product_id"];where x 是 0-9 之间的任何数字

也试过了,还是不行

        $i=0;
        while($rslt[$i]["product_id"]!="")
            {
            echo $i;
            //echo $rslt[4]["product_id"];                    
            echo $rslt[$i]["product_id"];
            $i++;
            }

【问题讨论】:

  • 你做错了什么?
  • @ExplosionPills 没有错,但是 $rslt[4] 中的数字-括号之间的数字是 {i: 之后的文本中的数字:即 4,但并不总是 4。可以是 0-9 之间的任意数字
  • 试试echo $rslt[mt_rand(0, 9)]["product_id"];
  • a:1:{i:4;a:17:{s:..... 你只有 array(4 => array(... 在你的序列化中,只有 $rslt[ 4]["product_id"] 将被定义
  • 根据 JSONLint - 你的 JSON 不是 VALID JSON。

标签: php function serialization numbers


【解决方案1】:

一旦你反序列化你的输入,你就有一个很好的旧 PHP 数组,相当于:

$rslt = array (
  4 => 
  array (
    'quantity' => 1,
    'product_id' => 5196,
    'category_id' => '209',
    'price' => 1,
    'tax' => '18.00',
    'tax_id' => '1',
    'description' => '',
    'product_name' => 'test',
    'thumb_image' => '',
    'ean' => '',
    'attributes' => 'a:0:{}',
    'attributes_value' => 
    array (
    ),
    'weight' => '0.0000',
    'vendor_id' => '0',
    'files' => 'a:0:{}',
    'freeattributes' => 'a:0:{}',
    'dependent_attr_serrialize' => 'a:0:{}',
  ),
);

要获取第一个元素,只需调用current(),就像使用任何其他数组一样:

$first_item = current($rslt);
print_r($first_item['product_id']);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2011-08-11
    • 2014-11-18
    • 1970-01-01
    • 2010-10-06
    相关资源
    最近更新 更多