[英]PHP Split array in subarrays
Note, array_chunk is not my solution (It seems to me). 注意,array_chunk不是我的解决方案(在我看来)。
I have an array of about 150.000 elements 我有大约150.000个元素的数组
Array
(
[0] => Array
(
[name] => Danilo
[phone] => 33568
)
[1] => Array
(
[name] => Alessandro
[phone] => 392222
)
[2] => Array
(
[name] => Alex
[phone] => 3922
)
[3] => Array
(
[name] => Capa
[phone] => 392
)
)
And so on. 等等。 I would split this array in several arrays, of (for example) 3.000 elements every one.
我会将这个数组分成几个数组,例如每个数组有3.000个元素。
I saw array_chunk, but it returns a single array with several subarray. 我看到了array_chunk,但是它返回了一个带有多个子数组的数组。
I need several subarray to store them in a database and elaborate in future. 我需要几个子数组将它们存储在数据库中,并在以后进行详细说明。
I'm getting crazy to write a snippet starting from that $temp and divide it into smaller array. 我发疯了,从$ temp开始编写一个片段,并将其分成较小的数组。
$size_chunks = 1;
$temp = array_chunk($recipients, $size_chunks);
foreach ($temp as $key=>$value)
{
if ($key<$size_chunks)
{
$to_store[] = $temp[$key];
}
//print_r($to_store);
// pseudo sql
// INSERT INTO table (sub_recipient) VALUES ($to_store);
$to_store = array();
}
So, every time that for loop end, reduce temp, store $to_store array and restart for others chunks. 因此,每次for循环结束时,降低温度,存储$ to_store数组,然后为其他块重新启动。
Thank you very much. 非常感谢你。
PS in my example chunk==1 because starting array is small... ;) 我的示例块中的PS == 1,因为起始数组很小...;)
With my example of chunk = 1, I need from starting array this 4 arrays: 在我的chunk = 1的示例中,我需要从数组开始这4个数组:
Array
(
[0] => Array
(
[name] => Danilo
[phone] => 33568
)
)
Array
(
[0] => Array
(
[name] => Alessandro
[phone] => 39222
)
)
Array
(
[0] => Array
(
[name] => Alex
[phone] => 39222
)
)
Array
(
[0] => Array
(
[name] => Capa
[phone] => 392
)
)
1 - With a starting array of 15.000 elements, and chunk of 3.000, I need in output (15.000 / 3.000) = 5 arrays. 1-以15.000个元素的起始数组和3.000个块为例,我需要输入(15.000 / 3.000)= 5个数组。 I will save them in database, so in DB I will have 5 rows (a row for every array).
我将它们保存在数据库中,因此在DB中,我将有5行(每个数组一行)。
2 - With a starting array of 4 elements, and chunk of 1, I need in output (4 / 1) = 4 arrays. 2-以4个元素为起始数组,块为1,我需要在输出(4/1)= 4个数组中输入。 I will save them in database, so in DB I will have 4 rows (a row for every array).
我将它们保存在数据库中,因此在DB中,我将有4行(每个数组一行)。
array_chunks()
already does what you want, you just have to save it: array_chunks()
已经array_chunks()
您的要求,只需保存即可:
$chunks = array_chunk($array, $size_chunks);
foreach ($chunks as $chunk) {
// save $chunk to your database
}
$recipients = Array(
Array("fdbvfdb","dsacsdcds"),
Array("hrloo","dacdsc"),
Array("dcsdc","adcsd"),
Array("dcsdc","adcsd")
);
$total = count($recipients);//count 150.000 elements
$i=1;
for($i=0;$i<$total;$i++){
$O = array_slice($recipients,$i,1);
print_r($O);
//Your insert/Save code
}
you can use this code there is uses Array_Slice 您可以使用此代码,还有使用Array_Slice
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.