将逗号分隔的逗号分隔成较小的部分

时间:2012-11-21 00:19:47

标签: php facebook string loops

将50个++号码(FB页面ID)的逗号分隔列表拆分为较小的块并一次处理它们 n 的最佳方法是什么?该列表将如下所示:

$likeslist="266037406871517,81337462601,34782298000891,56859608486,8797601255,48126111909968,8807449704,3634204295,6840064056,16627954050,7581229254,282681243370,356780606553962,207549746039055,13708123117519,204852972922619,407056596017784,584207664985882,11141618921610,66707529019,271953746236343,9576298621,40575497158,29252725868524,210237443769975,469586875072133,32693104762450,262744428996,506144412803606,52385706779438";

因为$ likeslist中的总数会有所不同(可能是数百个),使用explode或substr_count获取我们使用的总数是否更快? (问题1

$likesarray = explode(",", $likeslist);
$result = count($likeslist);

OR

$listtotal = substr_count($likeslist, ",") +1;

然后,我如何将$ likeslist分成较小的组(比如5)并循环遍历每组内的每个ID? (问题2

2 个答案:

答案 0 :(得分:0)

使用多维数组。

$likes = explode(",", $likesList);
$l5 = array(); // multi-dimensional array containing arrays of only 5 likes
$i = 0; // counter for how many items we have per sub-array
$c = 0; // counter for what index of $l5 we are on
foreach($likes as $l) {
    if ( $i >= 5 ) {
        $c++; // increment array index
        $i = 0; // reset counter for the next 5 entries
    }
    $l5[$c][] = $l;
    $i++;
}

答案 1 :(得分:0)

继续做一个大阵容。耗尽所有内存(并且可以在配置中更改内存限制)必须非常大。

要处理列表的各个部分,只需使用循环和array_slice()函数:

$likeslist = explode(',', $likeslist);    
$listLen = count($likeslist);
$chunkSize = 5;

for($offset=0; $offset<$listLen; $offset+=$chunkSize) {
    $subList = array_slice($likeslist, $offset, $chunkSize);
    // do whatever to your sublist 
    print_r($subList);
}