PHP - 从序列化数据中获取每4个值

时间:2012-02-02 14:23:38

标签: php

我有一个脚本,它带有许多文件名,然后序列化数据,序列化数据中可能有数百个文件名。

我希望能够做到的是每隔4个文件名回显一次。

我不太确定如何解决这个问题,如果有人可以提供帮助,我们将不胜感激。

以下是序列化数据的示例,它只有8条记录,因此只输出2个文件名

a:8:{i:0;s:62:"1328018910RYw4LKmf3yb2ZhCHcFB9VvPqGMTrxgXzdDpWQntJN7k6j8_o.jpg";i:1;s:62:"1328018910RYw4LKmf3yb2ZhCHcFB9VvPqGMTrxgXzdDpWQntJN7k6j8_s.jpg";i:2;s:62:"1328018910RYw4LKmf3yb2ZhCHcFB9VvPqGMTrxgXzdDpWQntJN7k6j8_t.jpg";i:3;s:63:"1328018910RYw4LKmf3yb2ZhCHcFB9VvPqGMTrxgXzdDpWQntJN7k6j8_st.jpg";i:4;s:62:"1328018917rdwfFQ3xBDgvLKZCH4j8qTpYkz2VmJ9y7XntRcNbMG6PWh_o.jpg";i:5;s:62:"1328018917rdwfFQ3xBDgvLKZCH4j8qTpYkz2VmJ9y7XntRcNbMG6PWh_s.jpg";i:6;s:62:"1328018917rdwfFQ3xBDgvLKZCH4j8qTpYkz2VmJ9y7XntRcNbMG6PWh_t.jpg";i:7;s:63:"1328018917rdwfFQ3xBDgvLKZCH4j8qTpYkz2VmJ9y7XntRcNbMG6PWh_st.jpg";}

2 个答案:

答案 0 :(得分:2)

您可以使用MOD运算符或简单的for循环来实现此目的:

$data = "a:8:{i:0;s:62:"1328018910RYw4LKmf3yb2ZhCHcFB9VvPqGMTrxgXzdDpWQntJN7k6j8_o.jpg";i:1;s:62:"1328018910RYw4LKmf3yb2ZhCHcFB9VvPqGMTrxgXzdDpWQntJN7k6j8_s.jpg";i:2;s:62:"1328018910RYw4LKmf3yb2ZhCHcFB9VvPqGMTrxgXzdDpWQntJN7k6j8_t.jpg";i:3;s:63:"1328018910RYw4LKmf3yb2ZhCHcFB9VvPqGMTrxgXzdDpWQntJN7k6j8_st.jpg";i:4;s:62:"1328018917rdwfFQ3xBDgvLKZCH4j8qTpYkz2VmJ9y7XntRcNbMG6PWh_o.jpg";i:5;s:62:"1328018917rdwfFQ3xBDgvLKZCH4j8qTpYkz2VmJ9y7XntRcNbMG6PWh_s.jpg";i:6;s:62:"1328018917rdwfFQ3xBDgvLKZCH4j8qTpYkz2VmJ9y7XntRcNbMG6PWh_t.jpg";i:7;s:63:"1328018917rdwfFQ3xBDgvLKZCH4j8qTpYkz2VmJ9y7XntRcNbMG6PWh_st.jpg";}"

$data = unserialize($data);
for($idata = 3; $idata <= count($data)-1; $idata += 4){
    echo $data[$idata].'<br />';
}

如果你想让mod操作符改为:

$data = unserialize($data);
$idata = 0;
foreach($data as $dataitem){
    if(($idata % 4) == 3){
        echo $dataitem.'<br />';
    }
}

Modulo是一个运算符,它将数字除以X并返回余数:

0 % 4 = 0
1 % 4 = 1
2 % 4 = 2
3 % 4 = 3
4 % 4 = 0
5 % 4 = 1
6 % 4 = 2
7 % 4 = 3
8 % 4 = 0
9 % 4 = 1

答案 1 :(得分:0)

您可以简单地序列化返回的数据......然后您可以捕获