2013-12-16 26 views
0

我有喜歡 -批大名單爲較小的批次

array(
[0] => (string)"A.1.failure", 
[1] => (string)"A.2.failure", 
[2] => (string)"A.3.failure", 
[3] => (string)"A.4.failure", 
[4] => (string)"B.1.failure", 
[5] => (string)"B.1.failure", 
. 
. 
) 

名單,我想使聲言如下─4.在這種情況下,分批捲曲電話,我想要的東西,喜歡 -

[0] => (string) 
     "&target=A.1.failure 
      &target=A.2.failure 
      &target=A.3.failure 
      &target=B.1.failure", 

[1] => (string) 
     "&target=B.2.failure 
      &target=B.3.failure 
      &target=B.4.failure 
      &target=C.1.failure", 

在PHP中是否有一種內置/常用的方法可以簡化此操作?Ç像代碼我寫變得太複雜,調試 -

private function _aggregate_metric_list_into_batches($metric_list) 
{ 
$batch_calls  = NULL; 
$batched_list = array(); 
$calls_per_batch = $this->_curl_call_batch_size; 

if ($this->_flag_skip_inactive_instances) 
{ 
    $running_instances = $this->_get_ip_of_running_instances(INSTANCE_ROLE_SPIDERMAN); 
} 

$num_of_batches = ceil(count($metric_list)/$calls_per_batch); 
var_dump($num_of_batches); 
for ($current_batch = 0; $current_batch < $num_of_batches; $current_batch++) 
{ 
    $batched_list[$current_batch] = array(); 

    // $batch_offset < count($metric_list)-1 so that $j doesn't roll upto $calls_per_batch at the last iteration. 
    $batch_offset = 0; 
    for ($j = 0; $j < $calls_per_batch && $batch_offset < count($metric_list) - 1; $j++) 
    { 
     $batch_offset = (($current_batch * $calls_per_batch) + $j); 
     $core_metric = $metric_list[$batch_offset]; 
     $exploded  = explode(".", $core_metric); 
     $metric_ip = $exploded[4]; 

     if ($this->_flag_skip_inactive_instances AND !in_array($metric_ip, $running_instances)) 
     { 
      // If --skip-inactive-instances flag is not NULL, skip those which aren't running. 
      if($this->_flag_verbosity) 
      { 
       Helper_Common::log_for_console_and_human("Ignoring $metric_ip.", LOG_TYPE_INFO); 
      } 
      continue; 
     } 
     if ($this->_apply_metric_function === WY_FALSE) 
     { 
      $prepared_metric = "&target=".$core_metric; 
     } 
     else 
     { 
      $prepared_metric = "&target=".$this->_metric_function."(".$core_metric.",".$this->_metric_function_arg.")"; 
     } 
     $batch_calls  = $batch_calls.$prepared_metric; 
    } 

    $batched_list[$current_batch] = $batch_calls; 
    $batch_calls   = ""; 
} 
+0

[array_slice](http://php.net/array_slice)? –

+0

不要使用捲曲來完成這類任務,這裏有很多潛在的失敗空間,而且很可能不安全。使用cron作業,而不是使用php shell腳本。 – burzum

+0

我正在查詢一個URL API。所以我*將不得不使用捲曲,對吧?也許我可以看看多線程捲曲或什麼的。 – erbdex

回答

2

使用array_chunk功能 實施例:

$input_array = array('A.1.failure', 'A.2.failure', 'A.3.failure', 'B.1.failure', 'B.2.failure', 'B.3.failure', 'B.4.failure'); 
print_r(array_chunk($input_array, 4)); 

它將塊它成每個數組中的元素

+0

哇。想象我在做什麼。 :D – erbdex

+0

呃!!!現在這是你想要的? – sergio

+0

我想你錯了。這真的是我想要的。謝謝。 – erbdex